Fossil SCM

Merge with trunk.

isaac.jurado 2013-06-25 22:15 git-better-import merge
Commit 995ed75f9aca1a6a5bcee246d51fe0e0d1ea5f43
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -1,2 +1,4 @@
1
+compat/openssl*
2
+compat/tcl*
13
fossil
24
fossil.exe
35
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -1,2 +1,4 @@
 
 
1 fossil
2 fossil.exe
3
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -1,2 +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
+1 -1
--- VERSION
+++ VERSION
@@ -1,1 +1,1 @@
1
-1.25
1
+1.26
22
--- VERSION
+++ VERSION
@@ -1,1 +1,1 @@
1 1.25
2
--- VERSION
+++ VERSION
@@ -1,1 +1,1 @@
1 1.26
2
+4
--- auto.def
+++ auto.def
@@ -60,10 +60,14 @@
6060
user-error "system sqlite3 not found"
6161
}
6262
6363
find_internal_sqlite
6464
}
65
+
66
+if {[string match *-solaris* [get-define host]]} {
67
+ define-append EXTRA_CFLAGS -D_XOPEN_SOURCE=500
68
+}
6569
6670
if {[opt-bool fossil-debug]} {
6771
define-append EXTRA_CFLAGS -DFOSSIL_DEBUG
6872
}
6973
7074
--- auto.def
+++ auto.def
@@ -60,10 +60,14 @@
60 user-error "system sqlite3 not found"
61 }
62
63 find_internal_sqlite
64 }
 
 
 
 
65
66 if {[opt-bool fossil-debug]} {
67 define-append EXTRA_CFLAGS -DFOSSIL_DEBUG
68 }
69
70
--- auto.def
+++ auto.def
@@ -60,10 +60,14 @@
60 user-error "system sqlite3 not found"
61 }
62
63 find_internal_sqlite
64 }
65
66 if {[string match *-solaris* [get-define host]]} {
67 define-append EXTRA_CFLAGS -D_XOPEN_SOURCE=500
68 }
69
70 if {[opt-bool fossil-debug]} {
71 define-append EXTRA_CFLAGS -DFOSSIL_DEBUG
72 }
73
74
+2 -2
--- src/add.c
+++ src/add.c
@@ -283,11 +283,11 @@
283283
284284
file_canonical_name(g.argv[i], &fullName, 0);
285285
zName = blob_str(&fullName);
286286
isDir = file_wd_isdir(zName);
287287
if( isDir==1 ){
288
- vfile_scan2(&fullName, nRoot-1, scanFlags, pClean, pIgnore);
288
+ vfile_scan(&fullName, nRoot-1, scanFlags, pClean, pIgnore);
289289
}else if( isDir==0 ){
290290
fossil_warning("not found: %s", zName);
291291
}else if( file_access(zName, R_OK) ){
292292
fossil_fatal("cannot open %s", zName);
293293
}else{
@@ -523,11 +523,11 @@
523523
n = strlen(g.zLocalRoot);
524524
blob_init(&path, g.zLocalRoot, n-1);
525525
/* now we read the complete file structure into a temp table */
526526
pClean = glob_create(zCleanFlag);
527527
pIgnore = glob_create(zIgnoreFlag);
528
- vfile_scan2(&path, blob_size(&path), scanFlags, pClean, pIgnore);
528
+ vfile_scan(&path, blob_size(&path), scanFlags, pClean, pIgnore);
529529
glob_free(pIgnore);
530530
glob_free(pClean);
531531
nAdd = add_files_in_sfile(vid);
532532
533533
/* step 2: search for missing files */
534534
--- src/add.c
+++ src/add.c
@@ -283,11 +283,11 @@
283
284 file_canonical_name(g.argv[i], &fullName, 0);
285 zName = blob_str(&fullName);
286 isDir = file_wd_isdir(zName);
287 if( isDir==1 ){
288 vfile_scan2(&fullName, nRoot-1, scanFlags, pClean, pIgnore);
289 }else if( isDir==0 ){
290 fossil_warning("not found: %s", zName);
291 }else if( file_access(zName, R_OK) ){
292 fossil_fatal("cannot open %s", zName);
293 }else{
@@ -523,11 +523,11 @@
523 n = strlen(g.zLocalRoot);
524 blob_init(&path, g.zLocalRoot, n-1);
525 /* now we read the complete file structure into a temp table */
526 pClean = glob_create(zCleanFlag);
527 pIgnore = glob_create(zIgnoreFlag);
528 vfile_scan2(&path, blob_size(&path), scanFlags, pClean, pIgnore);
529 glob_free(pIgnore);
530 glob_free(pClean);
531 nAdd = add_files_in_sfile(vid);
532
533 /* step 2: search for missing files */
534
--- src/add.c
+++ src/add.c
@@ -283,11 +283,11 @@
283
284 file_canonical_name(g.argv[i], &fullName, 0);
285 zName = blob_str(&fullName);
286 isDir = file_wd_isdir(zName);
287 if( isDir==1 ){
288 vfile_scan(&fullName, nRoot-1, scanFlags, pClean, pIgnore);
289 }else if( isDir==0 ){
290 fossil_warning("not found: %s", zName);
291 }else if( file_access(zName, R_OK) ){
292 fossil_fatal("cannot open %s", zName);
293 }else{
@@ -523,11 +523,11 @@
523 n = strlen(g.zLocalRoot);
524 blob_init(&path, g.zLocalRoot, n-1);
525 /* now we read the complete file structure into a temp table */
526 pClean = glob_create(zCleanFlag);
527 pIgnore = glob_create(zIgnoreFlag);
528 vfile_scan(&path, blob_size(&path), scanFlags, pClean, pIgnore);
529 glob_free(pIgnore);
530 glob_free(pClean);
531 nAdd = add_files_in_sfile(vid);
532
533 /* step 2: search for missing files */
534
+81 -32
--- src/bisect.c
+++ src/bisect.c
@@ -65,10 +65,12 @@
6565
} aBisectOption[] = {
6666
{ "auto-next", "on", "Automatically run \"bisect next\" after each "
6767
"\"bisect good\" or \"bisect bad\"" },
6868
{ "direct-only", "on", "Follow only primary parent-child links, not "
6969
"merges\n" },
70
+ { "display", "chart", "Command to run after \"next\". \"chart\", "
71
+ "\"log\", \"status\", or \"none\"" },
7072
};
7173
7274
/*
7375
** Return the value of a boolean bisect option.
7476
*/
@@ -165,10 +167,61 @@
165167
db_multi_exec(
166168
"REPLACE INTO vvar(name,value) VALUES('bisect-log',"
167169
"COALESCE((SELECT value||' ' FROM vvar WHERE name='bisect-log'),'')"
168170
" || '%d')", rid);
169171
}
172
+
173
+/*
174
+** Show a chart of bisect "good" and "bad" versions. The chart can be
175
+** sorted either chronologically by bisect time, or by check-in time.
176
+*/
177
+static void bisect_chart(int sortByCkinTime){
178
+ char *zLog = db_lget("bisect-log","");
179
+ Blob log, id;
180
+ Stmt q;
181
+ int cnt = 0;
182
+ blob_init(&log, zLog, -1);
183
+ db_multi_exec(
184
+ "CREATE TEMP TABLE bilog("
185
+ " seq INTEGER PRIMARY KEY," /* Sequence of events */
186
+ " stat TEXT," /* Type of occurrence */
187
+ " rid INTEGER" /* Check-in number */
188
+ ");"
189
+ );
190
+ db_prepare(&q, "INSERT OR IGNORE INTO bilog(seq,stat,rid)"
191
+ " VALUES(:seq,:stat,:rid)");
192
+ while( blob_token(&log, &id) ){
193
+ int rid = atoi(blob_str(&id));
194
+ db_bind_int(&q, ":seq", ++cnt);
195
+ db_bind_text(&q, ":stat", rid>0 ? "GOOD" : "BAD");
196
+ db_bind_int(&q, ":rid", rid>=0 ? rid : -rid);
197
+ db_step(&q);
198
+ db_reset(&q);
199
+ }
200
+ db_bind_int(&q, ":seq", ++cnt);
201
+ db_bind_text(&q, ":stat", "CURRENT");
202
+ db_bind_int(&q, ":rid", db_lget_int("checkout", 0));
203
+ db_step(&q);
204
+ db_finalize(&q);
205
+ db_prepare(&q,
206
+ "SELECT bilog.seq, bilog.stat,"
207
+ " substr(blob.uuid,1,16), datetime(event.mtime)"
208
+ " FROM bilog, blob, event"
209
+ " WHERE blob.rid=bilog.rid AND event.objid=bilog.rid"
210
+ " AND event.type='ci'"
211
+ " ORDER BY %s",
212
+ (sortByCkinTime ? "event.mtime DESC" : "bilog.rowid ASC")
213
+ );
214
+ while( db_step(&q)==SQLITE_ROW ){
215
+ fossil_print("%3d %-7s %s %s\n",
216
+ db_column_int(&q, 0),
217
+ db_column_text(&q, 1),
218
+ db_column_text(&q, 3),
219
+ db_column_text(&q, 2));
220
+ }
221
+ db_finalize(&q);
222
+}
170223
171224
/*
172225
** COMMAND: bisect
173226
**
174227
** Usage: %fossil bisect SUBCOMMAND ...
@@ -184,12 +237,15 @@
184237
**
185238
** Identify version VERSION as working. If VERSION is omitted,
186239
** the current checkout is marked as working.
187240
**
188241
** fossil bisect log
242
+** fossil bisect chart
189243
**
190
-** Show a log of "good" and "bad" versions
244
+** Show a log of "good" and "bad" versions. "bisect log" shows the
245
+** events in the order that they were tested. "bisect chart" shows
246
+** them in order of check-in.
191247
**
192248
** fossil bisect next
193249
**
194250
** Update to the next version that is halfway between the working and
195251
** non-working versions.
@@ -215,10 +271,11 @@
215271
** Summary:
216272
**
217273
** fossil bisect bad ?VERSION?
218274
** fossil bisect good ?VERSION?
219275
** fossil bisect log
276
+** fossil bisect chart
220277
** fossil bisect next
221278
** fossil bisect options
222279
** fossil bisect reset
223280
** fossil bisect status
224281
** fossil bisect undo
@@ -232,11 +289,11 @@
232289
usage("bad|good|log|next|options|reset|status|undo");
233290
}
234291
zCmd = g.argv[2];
235292
n = strlen(zCmd);
236293
if( n==0 ) zCmd = "-";
237
- if( memcmp(zCmd, "bad", n)==0 ){
294
+ if( strncmp(zCmd, "bad", n)==0 ){
238295
int ridBad;
239296
foundCmd = 1;
240297
if( g.argc==3 ){
241298
ridBad = db_lget_int("checkout",0);
242299
}else{
@@ -247,11 +304,11 @@
247304
if( bisect_option("auto-next") && db_lget_int("bisect-good",0)>0 ){
248305
zCmd = "next";
249306
n = 4;
250307
}
251308
}
252
- }else if( memcmp(zCmd, "good", n)==0 ){
309
+ }else if( strncmp(zCmd, "good", n)==0 ){
253310
int ridGood;
254311
foundCmd = 1;
255312
if( g.argc==3 ){
256313
ridGood = db_lget_int("checkout",0);
257314
}else{
@@ -262,11 +319,11 @@
262319
if( bisect_option("auto-next") && db_lget_int("bisect-bad",0)>0 ){
263320
zCmd = "next";
264321
n = 4;
265322
}
266323
}
267
- }else if( memcmp(zCmd, "undo", n)==0 ){
324
+ }else if( strncmp(zCmd, "undo", n)==0 ){
268325
char *zLog;
269326
Blob log, id;
270327
int ridBad = 0;
271328
int ridGood = 0;
272329
int cnt = 0, i;
@@ -298,12 +355,14 @@
298355
n = 4;
299356
}
300357
}
301358
/* No else here so that the above commands can morph themselves into
302359
** a "next" command */
303
- if( memcmp(zCmd, "next", n)==0 ){
360
+ if( strncmp(zCmd, "next", n)==0 ){
304361
PathNode *pMid;
362
+ char *zDisplay = db_lget("bisect-display","chart");
363
+ int m = (int)strlen(zDisplay);
305364
bisect_path();
306365
pMid = path_midpoint();
307366
if( pMid==0 ){
308367
fossil_print("bisect complete\n");
309368
}else{
@@ -311,33 +370,23 @@
311370
g.argv[2] = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", pMid->rid);
312371
g.argc = 3;
313372
g.fNoSync = 1;
314373
update_cmd();
315374
}
316
- bisect_list(1);
317
- }else if( memcmp(zCmd, "log", n)==0 ){
318
- char *zLog = db_lget("bisect-log","");
319
- Blob log, id;
320
- Stmt q;
321
- int cnt = 0;
322
- blob_init(&log, zLog, -1);
323
- db_prepare(&q, "SELECT substr(blob.uuid,1,16), datetime(event.mtime)"
324
- " FROM blob, event"
325
- " WHERE blob.rid=:rid AND event.objid=:rid"
326
- " AND event.type='ci'");
327
- while( blob_token(&log, &id) ){
328
- int rid = atoi(blob_str(&id));
329
- db_bind_int(&q, ":rid", rid<0 ? -rid : rid);
330
- if( db_step(&q)==SQLITE_ROW ){
331
- cnt++;
332
- fossil_print("%3d %-4s %s %s\n", cnt, rid<0 ? "BAD" : "GOOD",
333
- db_column_text(&q, 1), db_column_text(&q, 0));
334
- }
335
- db_reset(&q);
336
- }
337
- db_finalize(&q);
338
- }else if( memcmp(zCmd, "options", n)==0 ){
375
+
376
+ if( strncmp(zDisplay,"chart",m)==0 ){
377
+ bisect_chart(1);
378
+ }else if( strncmp(zDisplay, "log", m)==0 ){
379
+ bisect_chart(0);
380
+ }else if( strncmp(zDisplay, "status", m)==0 ){
381
+ bisect_list(1);
382
+ }
383
+ }else if( strncmp(zCmd, "log", n)==0 ){
384
+ bisect_chart(0);
385
+ }else if( strncmp(zCmd, "chart", n)==0 ){
386
+ bisect_chart(1);
387
+ }else if( strncmp(zCmd, "options", n)==0 ){
339388
if( g.argc==3 ){
340389
unsigned int i;
341390
for(i=0; i<sizeof(aBisectOption)/sizeof(aBisectOption[0]); i++){
342391
char *z = mprintf("bisect-%s", aBisectOption[i].zName);
343392
fossil_print(" %-15s %-6s ", aBisectOption[i].zName,
@@ -363,20 +412,20 @@
363412
fossil_fatal("no such bisect option: %s", g.argv[3]);
364413
}
365414
}else{
366415
usage("bisect option ?NAME? ?VALUE?");
367416
}
368
- }else if( memcmp(zCmd, "reset", n)==0 ){
417
+ }else if( strncmp(zCmd, "reset", n)==0 ){
369418
db_multi_exec(
370419
"DELETE FROM vvar WHERE name IN "
371420
" ('bisect-good', 'bisect-bad', 'bisect-log')"
372421
);
373
- }else if( memcmp(zCmd, "vlist", n)==0
374
- || memcmp(zCmd, "ls", n)==0
375
- || memcmp(zCmd, "status", n)==0
422
+ }else if( strncmp(zCmd, "vlist", n)==0
423
+ || strncmp(zCmd, "ls", n)==0
424
+ || strncmp(zCmd, "status", n)==0
376425
){
377426
int fAll = find_option("all", "a", 0)!=0;
378427
bisect_list(!fAll);
379428
}else if( !foundCmd ){
380429
usage("bad|good|log|next|options|reset|status|undo");
381430
}
382431
}
383432
--- src/bisect.c
+++ src/bisect.c
@@ -65,10 +65,12 @@
65 } aBisectOption[] = {
66 { "auto-next", "on", "Automatically run \"bisect next\" after each "
67 "\"bisect good\" or \"bisect bad\"" },
68 { "direct-only", "on", "Follow only primary parent-child links, not "
69 "merges\n" },
 
 
70 };
71
72 /*
73 ** Return the value of a boolean bisect option.
74 */
@@ -165,10 +167,61 @@
165 db_multi_exec(
166 "REPLACE INTO vvar(name,value) VALUES('bisect-log',"
167 "COALESCE((SELECT value||' ' FROM vvar WHERE name='bisect-log'),'')"
168 " || '%d')", rid);
169 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
171 /*
172 ** COMMAND: bisect
173 **
174 ** Usage: %fossil bisect SUBCOMMAND ...
@@ -184,12 +237,15 @@
184 **
185 ** Identify version VERSION as working. If VERSION is omitted,
186 ** the current checkout is marked as working.
187 **
188 ** fossil bisect log
 
189 **
190 ** Show a log of "good" and "bad" versions
 
 
191 **
192 ** fossil bisect next
193 **
194 ** Update to the next version that is halfway between the working and
195 ** non-working versions.
@@ -215,10 +271,11 @@
215 ** Summary:
216 **
217 ** fossil bisect bad ?VERSION?
218 ** fossil bisect good ?VERSION?
219 ** fossil bisect log
 
220 ** fossil bisect next
221 ** fossil bisect options
222 ** fossil bisect reset
223 ** fossil bisect status
224 ** fossil bisect undo
@@ -232,11 +289,11 @@
232 usage("bad|good|log|next|options|reset|status|undo");
233 }
234 zCmd = g.argv[2];
235 n = strlen(zCmd);
236 if( n==0 ) zCmd = "-";
237 if( memcmp(zCmd, "bad", n)==0 ){
238 int ridBad;
239 foundCmd = 1;
240 if( g.argc==3 ){
241 ridBad = db_lget_int("checkout",0);
242 }else{
@@ -247,11 +304,11 @@
247 if( bisect_option("auto-next") && db_lget_int("bisect-good",0)>0 ){
248 zCmd = "next";
249 n = 4;
250 }
251 }
252 }else if( memcmp(zCmd, "good", n)==0 ){
253 int ridGood;
254 foundCmd = 1;
255 if( g.argc==3 ){
256 ridGood = db_lget_int("checkout",0);
257 }else{
@@ -262,11 +319,11 @@
262 if( bisect_option("auto-next") && db_lget_int("bisect-bad",0)>0 ){
263 zCmd = "next";
264 n = 4;
265 }
266 }
267 }else if( memcmp(zCmd, "undo", n)==0 ){
268 char *zLog;
269 Blob log, id;
270 int ridBad = 0;
271 int ridGood = 0;
272 int cnt = 0, i;
@@ -298,12 +355,14 @@
298 n = 4;
299 }
300 }
301 /* No else here so that the above commands can morph themselves into
302 ** a "next" command */
303 if( memcmp(zCmd, "next", n)==0 ){
304 PathNode *pMid;
 
 
305 bisect_path();
306 pMid = path_midpoint();
307 if( pMid==0 ){
308 fossil_print("bisect complete\n");
309 }else{
@@ -311,33 +370,23 @@
311 g.argv[2] = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", pMid->rid);
312 g.argc = 3;
313 g.fNoSync = 1;
314 update_cmd();
315 }
316 bisect_list(1);
317 }else if( memcmp(zCmd, "log", n)==0 ){
318 char *zLog = db_lget("bisect-log","");
319 Blob log, id;
320 Stmt q;
321 int cnt = 0;
322 blob_init(&log, zLog, -1);
323 db_prepare(&q, "SELECT substr(blob.uuid,1,16), datetime(event.mtime)"
324 " FROM blob, event"
325 " WHERE blob.rid=:rid AND event.objid=:rid"
326 " AND event.type='ci'");
327 while( blob_token(&log, &id) ){
328 int rid = atoi(blob_str(&id));
329 db_bind_int(&q, ":rid", rid<0 ? -rid : rid);
330 if( db_step(&q)==SQLITE_ROW ){
331 cnt++;
332 fossil_print("%3d %-4s %s %s\n", cnt, rid<0 ? "BAD" : "GOOD",
333 db_column_text(&q, 1), db_column_text(&q, 0));
334 }
335 db_reset(&q);
336 }
337 db_finalize(&q);
338 }else if( memcmp(zCmd, "options", n)==0 ){
339 if( g.argc==3 ){
340 unsigned int i;
341 for(i=0; i<sizeof(aBisectOption)/sizeof(aBisectOption[0]); i++){
342 char *z = mprintf("bisect-%s", aBisectOption[i].zName);
343 fossil_print(" %-15s %-6s ", aBisectOption[i].zName,
@@ -363,20 +412,20 @@
363 fossil_fatal("no such bisect option: %s", g.argv[3]);
364 }
365 }else{
366 usage("bisect option ?NAME? ?VALUE?");
367 }
368 }else if( memcmp(zCmd, "reset", n)==0 ){
369 db_multi_exec(
370 "DELETE FROM vvar WHERE name IN "
371 " ('bisect-good', 'bisect-bad', 'bisect-log')"
372 );
373 }else if( memcmp(zCmd, "vlist", n)==0
374 || memcmp(zCmd, "ls", n)==0
375 || memcmp(zCmd, "status", n)==0
376 ){
377 int fAll = find_option("all", "a", 0)!=0;
378 bisect_list(!fAll);
379 }else if( !foundCmd ){
380 usage("bad|good|log|next|options|reset|status|undo");
381 }
382 }
383
--- src/bisect.c
+++ src/bisect.c
@@ -65,10 +65,12 @@
65 } aBisectOption[] = {
66 { "auto-next", "on", "Automatically run \"bisect next\" after each "
67 "\"bisect good\" or \"bisect bad\"" },
68 { "direct-only", "on", "Follow only primary parent-child links, not "
69 "merges\n" },
70 { "display", "chart", "Command to run after \"next\". \"chart\", "
71 "\"log\", \"status\", or \"none\"" },
72 };
73
74 /*
75 ** Return the value of a boolean bisect option.
76 */
@@ -165,10 +167,61 @@
167 db_multi_exec(
168 "REPLACE INTO vvar(name,value) VALUES('bisect-log',"
169 "COALESCE((SELECT value||' ' FROM vvar WHERE name='bisect-log'),'')"
170 " || '%d')", rid);
171 }
172
173 /*
174 ** Show a chart of bisect "good" and "bad" versions. The chart can be
175 ** sorted either chronologically by bisect time, or by check-in time.
176 */
177 static void bisect_chart(int sortByCkinTime){
178 char *zLog = db_lget("bisect-log","");
179 Blob log, id;
180 Stmt q;
181 int cnt = 0;
182 blob_init(&log, zLog, -1);
183 db_multi_exec(
184 "CREATE TEMP TABLE bilog("
185 " seq INTEGER PRIMARY KEY," /* Sequence of events */
186 " stat TEXT," /* Type of occurrence */
187 " rid INTEGER" /* Check-in number */
188 ");"
189 );
190 db_prepare(&q, "INSERT OR IGNORE INTO bilog(seq,stat,rid)"
191 " VALUES(:seq,:stat,:rid)");
192 while( blob_token(&log, &id) ){
193 int rid = atoi(blob_str(&id));
194 db_bind_int(&q, ":seq", ++cnt);
195 db_bind_text(&q, ":stat", rid>0 ? "GOOD" : "BAD");
196 db_bind_int(&q, ":rid", rid>=0 ? rid : -rid);
197 db_step(&q);
198 db_reset(&q);
199 }
200 db_bind_int(&q, ":seq", ++cnt);
201 db_bind_text(&q, ":stat", "CURRENT");
202 db_bind_int(&q, ":rid", db_lget_int("checkout", 0));
203 db_step(&q);
204 db_finalize(&q);
205 db_prepare(&q,
206 "SELECT bilog.seq, bilog.stat,"
207 " substr(blob.uuid,1,16), datetime(event.mtime)"
208 " FROM bilog, blob, event"
209 " WHERE blob.rid=bilog.rid AND event.objid=bilog.rid"
210 " AND event.type='ci'"
211 " ORDER BY %s",
212 (sortByCkinTime ? "event.mtime DESC" : "bilog.rowid ASC")
213 );
214 while( db_step(&q)==SQLITE_ROW ){
215 fossil_print("%3d %-7s %s %s\n",
216 db_column_int(&q, 0),
217 db_column_text(&q, 1),
218 db_column_text(&q, 3),
219 db_column_text(&q, 2));
220 }
221 db_finalize(&q);
222 }
223
224 /*
225 ** COMMAND: bisect
226 **
227 ** Usage: %fossil bisect SUBCOMMAND ...
@@ -184,12 +237,15 @@
237 **
238 ** Identify version VERSION as working. If VERSION is omitted,
239 ** the current checkout is marked as working.
240 **
241 ** fossil bisect log
242 ** fossil bisect chart
243 **
244 ** Show a log of "good" and "bad" versions. "bisect log" shows the
245 ** events in the order that they were tested. "bisect chart" shows
246 ** them in order of check-in.
247 **
248 ** fossil bisect next
249 **
250 ** Update to the next version that is halfway between the working and
251 ** non-working versions.
@@ -215,10 +271,11 @@
271 ** Summary:
272 **
273 ** fossil bisect bad ?VERSION?
274 ** fossil bisect good ?VERSION?
275 ** fossil bisect log
276 ** fossil bisect chart
277 ** fossil bisect next
278 ** fossil bisect options
279 ** fossil bisect reset
280 ** fossil bisect status
281 ** fossil bisect undo
@@ -232,11 +289,11 @@
289 usage("bad|good|log|next|options|reset|status|undo");
290 }
291 zCmd = g.argv[2];
292 n = strlen(zCmd);
293 if( n==0 ) zCmd = "-";
294 if( strncmp(zCmd, "bad", n)==0 ){
295 int ridBad;
296 foundCmd = 1;
297 if( g.argc==3 ){
298 ridBad = db_lget_int("checkout",0);
299 }else{
@@ -247,11 +304,11 @@
304 if( bisect_option("auto-next") && db_lget_int("bisect-good",0)>0 ){
305 zCmd = "next";
306 n = 4;
307 }
308 }
309 }else if( strncmp(zCmd, "good", n)==0 ){
310 int ridGood;
311 foundCmd = 1;
312 if( g.argc==3 ){
313 ridGood = db_lget_int("checkout",0);
314 }else{
@@ -262,11 +319,11 @@
319 if( bisect_option("auto-next") && db_lget_int("bisect-bad",0)>0 ){
320 zCmd = "next";
321 n = 4;
322 }
323 }
324 }else if( strncmp(zCmd, "undo", n)==0 ){
325 char *zLog;
326 Blob log, id;
327 int ridBad = 0;
328 int ridGood = 0;
329 int cnt = 0, i;
@@ -298,12 +355,14 @@
355 n = 4;
356 }
357 }
358 /* No else here so that the above commands can morph themselves into
359 ** a "next" command */
360 if( strncmp(zCmd, "next", n)==0 ){
361 PathNode *pMid;
362 char *zDisplay = db_lget("bisect-display","chart");
363 int m = (int)strlen(zDisplay);
364 bisect_path();
365 pMid = path_midpoint();
366 if( pMid==0 ){
367 fossil_print("bisect complete\n");
368 }else{
@@ -311,33 +370,23 @@
370 g.argv[2] = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", pMid->rid);
371 g.argc = 3;
372 g.fNoSync = 1;
373 update_cmd();
374 }
375
376 if( strncmp(zDisplay,"chart",m)==0 ){
377 bisect_chart(1);
378 }else if( strncmp(zDisplay, "log", m)==0 ){
379 bisect_chart(0);
380 }else if( strncmp(zDisplay, "status", m)==0 ){
381 bisect_list(1);
382 }
383 }else if( strncmp(zCmd, "log", n)==0 ){
384 bisect_chart(0);
385 }else if( strncmp(zCmd, "chart", n)==0 ){
386 bisect_chart(1);
387 }else if( strncmp(zCmd, "options", n)==0 ){
 
 
 
 
 
 
 
 
 
 
388 if( g.argc==3 ){
389 unsigned int i;
390 for(i=0; i<sizeof(aBisectOption)/sizeof(aBisectOption[0]); i++){
391 char *z = mprintf("bisect-%s", aBisectOption[i].zName);
392 fossil_print(" %-15s %-6s ", aBisectOption[i].zName,
@@ -363,20 +412,20 @@
412 fossil_fatal("no such bisect option: %s", g.argv[3]);
413 }
414 }else{
415 usage("bisect option ?NAME? ?VALUE?");
416 }
417 }else if( strncmp(zCmd, "reset", n)==0 ){
418 db_multi_exec(
419 "DELETE FROM vvar WHERE name IN "
420 " ('bisect-good', 'bisect-bad', 'bisect-log')"
421 );
422 }else if( strncmp(zCmd, "vlist", n)==0
423 || strncmp(zCmd, "ls", n)==0
424 || strncmp(zCmd, "status", n)==0
425 ){
426 int fAll = find_option("all", "a", 0)!=0;
427 bisect_list(!fAll);
428 }else if( !foundCmd ){
429 usage("bad|good|log|next|options|reset|status|undo");
430 }
431 }
432
+154 -39
--- src/checkin.c
+++ src/checkin.c
@@ -39,15 +39,36 @@
3939
){
4040
Stmt q;
4141
int nPrefix = strlen(zPrefix);
4242
int nErr = 0;
4343
Blob rewrittenPathname;
44
+ Blob where;
45
+ const char *zName;
46
+ int i;
47
+
48
+ blob_zero(&where);
49
+ for(i=2; i<g.argc; i++) {
50
+ Blob fname;
51
+ file_tree_name(g.argv[i], &fname, 1);
52
+ zName = blob_str(&fname);
53
+ if( fossil_strcmp(zName, ".")==0 ) {
54
+ blob_reset(&where);
55
+ break;
56
+ }
57
+ blob_appendf(&where, " %s (pathname=%Q %s) "
58
+ "OR (pathname>'%q/' %s AND pathname<'%q0' %s)",
59
+ (blob_size(&where)>0) ? "OR" : "AND", zName,
60
+ filename_collation(), zName, filename_collation(),
61
+ zName, filename_collation());
62
+ }
63
+
4464
db_prepare(&q,
4565
"SELECT pathname, deleted, chnged, rid, coalesce(origname!=pathname,0)"
4666
" FROM vfile "
47
- " WHERE is_selected(id)"
48
- " AND (chnged OR deleted OR rid=0 OR pathname!=origname) ORDER BY 1"
67
+ " WHERE is_selected(id) %s"
68
+ " AND (chnged OR deleted OR rid=0 OR pathname!=origname) ORDER BY 1",
69
+ blob_str(&where)
4970
);
5071
blob_zero(&rewrittenPathname);
5172
while( db_step(&q)==SQLITE_ROW ){
5273
const char *zPathname = db_column_text(&q,0);
5374
const char *zDisplayName = zPathname;
@@ -94,10 +115,12 @@
94115
}else{
95116
blob_appendf(report, "EDITED %s\n", zDisplayName);
96117
}
97118
}else if( isRenamed ){
98119
blob_appendf(report, "RENAMED %s\n", zDisplayName);
120
+ }else{
121
+ report->nUsed -= nPrefix;
99122
}
100123
free(zFullName);
101124
}
102125
blob_reset(&rewrittenPathname);
103126
db_finalize(&q);
@@ -217,14 +240,15 @@
217240
}
218241
219242
/*
220243
** COMMAND: ls
221244
**
222
-** Usage: %fossil ls ?OPTIONS? ?VERSION?
245
+** Usage: %fossil ls ?OPTIONS? ?VERSION? ?FILENAMES?
223246
**
224247
** Show the names of all files in the current checkout. The -v provides
225
-** extra information about each file.
248
+** extra information about each file. If FILENAMES are included, the only
249
+** the files listed (or their children if they are directories) are shown.
226250
**
227251
** Options:
228252
** --age Show when each file was committed
229253
** -v|--verbose Provide extra information about each file.
230254
**
@@ -234,10 +258,13 @@
234258
int vid;
235259
Stmt q;
236260
int verboseFlag;
237261
int showAge;
238262
char *zOrderBy = "pathname";
263
+ Blob where;
264
+ int i;
265
+ const char *zName;
239266
240267
verboseFlag = find_option("verbose","v", 0)!=0;
241268
if( !verboseFlag ){
242269
verboseFlag = find_option("l","l", 0)!=0; /* deprecated */
243270
}
@@ -250,25 +277,41 @@
250277
}else{
251278
zOrderBy = "mtime DESC";
252279
}
253280
}
254281
verify_all_options();
282
+ blob_zero(&where);
283
+ for(i=2; i<g.argc; i++){
284
+ Blob fname;
285
+ file_tree_name(g.argv[i], &fname, 1);
286
+ zName = blob_str(&fname);
287
+ if( fossil_strcmp(zName, ".")==0 ) {
288
+ blob_reset(&where);
289
+ break;
290
+ }
291
+ blob_appendf(&where, " %s (pathname=%Q %s) "
292
+ "OR (pathname>'%q/' %s AND pathname<'%q0' %s)",
293
+ (blob_size(&where)>0) ? "OR" : "WHERE", zName,
294
+ filename_collation(), zName, filename_collation(),
295
+ zName, filename_collation());
296
+ }
255297
vfile_check_signature(vid, 0);
256298
if( showAge ){
257299
db_prepare(&q,
258300
"SELECT pathname, deleted, rid, chnged, coalesce(origname!=pathname,0),"
259301
" datetime(checkin_mtime(%d,rid),'unixepoch','localtime')"
260
- " FROM vfile"
261
- " ORDER BY %s", vid, zOrderBy
302
+ " FROM vfile %s"
303
+ " ORDER BY %s", vid, blob_str(&where), zOrderBy
262304
);
263305
}else{
264306
db_prepare(&q,
265307
"SELECT pathname, deleted, rid, chnged, coalesce(origname!=pathname,0)"
266
- " FROM vfile"
267
- " ORDER BY %s", zOrderBy
308
+ " FROM vfile %s"
309
+ " ORDER BY %s", blob_str(&where), zOrderBy
268310
);
269311
}
312
+ blob_reset(&where);
270313
while( db_step(&q)==SQLITE_ROW ){
271314
const char *zPathname = db_column_text(&q,0);
272315
int isDeleted = db_column_int(&q, 1);
273316
int isNew = db_column_int(&q,2)==0;
274317
int chnged = db_column_int(&q,3);
@@ -297,17 +340,66 @@
297340
}
298341
free(zFullName);
299342
}
300343
db_finalize(&q);
301344
}
345
+
346
+/*
347
+** Create a TEMP table named SFILE and add all unmanaged files named on the command-line
348
+** to that table. If directories are named, then add all unmanaged files contained
349
+** underneath those directories. If there are no files or directories named on the
350
+** command-line, then add all unmanaged files anywhere in the checkout.
351
+*/
352
+static void locate_unmanaged_files(
353
+ int argc, /* Number of command-line arguments to examine */
354
+ char **argv, /* values of command-line arguments */
355
+ unsigned scanFlags, /* Zero or more SCAN_xxx flags */
356
+ Glob *pIgnore1, /* Do not add files that match this GLOB */
357
+ Glob *pIgnore2 /* Omit files matching this GLOB too */
358
+){
359
+ Blob name; /* Name of a candidate file or directory */
360
+ char *zName; /* Name of a candidate file or directory */
361
+ int isDir; /* 1 for a directory, 0 if doesn't exist, 2 for anything else */
362
+ int i; /* Loop counter */
363
+ int nRoot; /* length of g.zLocalRoot */
364
+
365
+ db_multi_exec("CREATE TEMP TABLE sfile(x TEXT PRIMARY KEY %s)",
366
+ filename_collation());
367
+ nRoot = (int)strlen(g.zLocalRoot);
368
+ if( argc==0 ){
369
+ blob_init(&name, g.zLocalRoot, nRoot - 1);
370
+ vfile_scan(&name, blob_size(&name), scanFlags, pIgnore1, pIgnore2);
371
+ blob_reset(&name);
372
+ }else{
373
+ for(i=0; i<argc; i++){
374
+ file_canonical_name(argv[i], &name, 0);
375
+ zName = blob_str(&name);
376
+ isDir = file_wd_isdir(zName);
377
+ if( isDir==1 ){
378
+ vfile_scan(&name, nRoot-1, scanFlags, pIgnore1, pIgnore2);
379
+ }else if( isDir==0 ){
380
+ fossil_warning("not found: %s", &zName[nRoot]);
381
+ }else if( file_access(zName, R_OK) ){
382
+ fossil_fatal("cannot open %s", &zName[nRoot]);
383
+ }else{
384
+ db_multi_exec(
385
+ "INSERT OR IGNORE INTO sfile(x) VALUES(%Q)",
386
+ &zName[nRoot]
387
+ );
388
+ }
389
+ blob_reset(&name);
390
+ }
391
+ }
392
+}
302393
303394
/*
304395
** COMMAND: extras
305
-** Usage: %fossil extras ?OPTIONS?
396
+** Usage: %fossil extras ?OPTIONS? ?PATH1 ...?
306397
**
307398
** Print a list of all files in the source tree that are not part of
308
-** the current checkout. See also the "clean" command.
399
+** the current checkout. See also the "clean" command. If paths are
400
+** specified, only files in the given directories will be listed.
309401
**
310402
** Files and subdirectories whose names begin with "." are normally
311403
** ignored but can be included by adding the --dotfiles option.
312404
**
313405
** The GLOBPATTERN is a comma-separated list of GLOB expressions for
@@ -326,13 +418,11 @@
326418
** directory.
327419
**
328420
** See also: changes, clean, status
329421
*/
330422
void extra_cmd(void){
331
- Blob path;
332423
Stmt q;
333
- int n;
334424
const char *zIgnoreFlag = find_option("ignore",0,1);
335425
unsigned scanFlags = find_option("dotfiles",0,0)!=0 ? SCAN_ALL : 0;
336426
int cwdRelative = 0;
337427
Glob *pIgnore;
338428
Blob rewrittenPathname;
@@ -340,19 +430,15 @@
340430
341431
if( find_option("temp",0,0)!=0 ) scanFlags |= SCAN_TEMP;
342432
capture_case_sensitive_option();
343433
db_must_be_within_tree();
344434
cwdRelative = determine_cwd_relative_option();
345
- db_multi_exec("CREATE TEMP TABLE sfile(x TEXT PRIMARY KEY %s)",
346
- filename_collation());
347
- n = strlen(g.zLocalRoot);
348
- blob_init(&path, g.zLocalRoot, n-1);
349435
if( zIgnoreFlag==0 ){
350436
zIgnoreFlag = db_get("ignore-glob", 0);
351437
}
352438
pIgnore = glob_create(zIgnoreFlag);
353
- vfile_scan(&path, blob_size(&path), scanFlags, pIgnore);
439
+ locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore, 0);
354440
glob_free(pIgnore);
355441
db_prepare(&q,
356442
"SELECT x FROM sfile"
357443
" WHERE x NOT IN (%s)"
358444
" ORDER BY 1",
@@ -377,15 +463,16 @@
377463
db_finalize(&q);
378464
}
379465
380466
/*
381467
** COMMAND: clean
382
-** Usage: %fossil clean ?OPTIONS?
468
+** Usage: %fossil clean ?OPTIONS? ?PATH1 ...?
383469
**
384470
** Delete all "extra" files in the source tree. "Extra" files are
385471
** files that are not officially part of the checkout. This operation
386
-** cannot be undone.
472
+** cannot be undone. If paths are specified, only the directories or
473
+** files specified will be considered for cleaning.
387474
**
388475
** You will be prompted before removing each eligible file unless the
389476
** --force flag is in use or it matches the --clean option. The
390477
** GLOBPATTERN specified by the "ignore-glob" setting is used if the
391478
** --ignore option is omitted, the same with "clean-glob" and --clean
@@ -417,14 +504,14 @@
417504
*/
418505
void clean_cmd(void){
419506
int allFlag, dryRunFlag, verboseFlag;
420507
unsigned scanFlags = 0;
421508
const char *zIgnoreFlag, *zKeepFlag, *zCleanFlag;
422
- Blob path, repo;
509
+ Blob repo;
423510
Stmt q;
424
- int n;
425511
Glob *pIgnore, *pKeep, *pClean;
512
+ int nRoot;
426513
427514
dryRunFlag = find_option("dry-run","n",0)!=0;
428515
if( !dryRunFlag ){
429516
dryRunFlag = find_option("test",0,0)!=0; /* deprecated */
430517
}
@@ -445,18 +532,14 @@
445532
}
446533
if( zCleanFlag==0 ){
447534
zCleanFlag = db_get("clean-glob", 0);
448535
}
449536
verify_all_options();
450
- db_multi_exec("CREATE TEMP TABLE sfile(x TEXT PRIMARY KEY %s)",
451
- filename_collation());
452
- n = strlen(g.zLocalRoot);
453
- blob_init(&path, g.zLocalRoot, n-1);
454537
pIgnore = glob_create(zIgnoreFlag);
455538
pKeep = glob_create(zKeepFlag);
456539
pClean = glob_create(zCleanFlag);
457
- vfile_scan2(&path, blob_size(&path), scanFlags, pIgnore, pKeep);
540
+ locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore, pKeep);
458541
glob_free(pKeep);
459542
glob_free(pIgnore);
460543
db_prepare(&q,
461544
"SELECT %Q || x FROM sfile"
462545
" WHERE x NOT IN (%s)"
@@ -465,17 +548,18 @@
465548
);
466549
if( file_tree_name(g.zRepositoryName, &repo, 0) ){
467550
db_multi_exec("DELETE FROM sfile WHERE x=%B", &repo);
468551
}
469552
db_multi_exec("DELETE FROM sfile WHERE x IN (SELECT pathname FROM vfile)");
553
+ nRoot = (int)strlen(g.zLocalRoot);
470554
while( db_step(&q)==SQLITE_ROW ){
471555
const char *zName = db_column_text(&q, 0);
472
- if( !allFlag && !dryRunFlag && !glob_match(pClean, zName+n) ){
556
+ if( !allFlag && !dryRunFlag && !glob_match(pClean, zName+nRoot) ){
473557
Blob ans;
474558
char cReply;
475559
char *prompt = mprintf("Remove unmanaged file \"%s\" (a=all/y/N)? ",
476
- zName+n);
560
+ zName+nRoot);
477561
blob_zero(&ans);
478562
prompt_user(prompt, &ans);
479563
cReply = blob_str(&ans)[0];
480564
if( cReply=='a' || cReply=='A' ){
481565
allFlag = 1;
@@ -484,11 +568,11 @@
484568
continue;
485569
}
486570
blob_reset(&ans);
487571
}
488572
if( verboseFlag || dryRunFlag ){
489
- fossil_print("Removed unmanaged file: %s\n", zName+n);
573
+ fossil_print("Removed unmanaged file: %s\n", zName+nRoot);
490574
}
491575
if( !dryRunFlag ){
492576
file_delete(zName);
493577
}
494578
}
@@ -657,29 +741,60 @@
657741
**
658742
** Returns 1 if there was a warning, 0 otherwise.
659743
*/
660744
int select_commit_files(void){
661745
int result = 0;
746
+ assert( g.aCommitFile==0 );
662747
if( g.argc>2 ){
663748
int ii, jj=0;
664
- Blob b;
665
- blob_zero(&b);
666
- g.aCommitFile = fossil_malloc(sizeof(int)*(g.argc-1));
749
+ Blob fname;
750
+ int isDir;
751
+ Stmt q;
752
+ const char *zCollate;
753
+ Bag toCommit;
667754
755
+ zCollate = filename_collation();
756
+ blob_zero(&fname);
757
+ bag_init(&toCommit);
668758
for(ii=2; ii<g.argc; ii++){
669
- int iId;
670
- file_tree_name(g.argv[ii], &b, 1);
671
- iId = db_int(-1, "SELECT id FROM vfile WHERE pathname=%Q", blob_str(&b));
672
- if( iId<0 ){
759
+ int cnt = 0;
760
+ file_tree_name(g.argv[ii], &fname, 1);
761
+ if( fossil_strcmp(blob_str(&fname),".")==0 ){
762
+ bag_clear(&toCommit);
763
+ return result;
764
+ }
765
+ isDir = file_isdir(g.argv[ii]);
766
+ if( isDir==1 ){
767
+ db_prepare(&q,
768
+ "SELECT id FROM vfile WHERE pathname>'%q/' %s AND pathname<'%q0'",
769
+ blob_str(&fname), zCollate, blob_str(&fname), zCollate);
770
+ }else if( isDir==2 ){
771
+ db_prepare(&q,
772
+ "SELECT id FROM vfile WHERE pathname=%Q",
773
+ blob_str(&fname), zCollate);
774
+ }else{
775
+ fossil_warning("not found: %s", g.argv[ii]);
776
+ result = 1;
777
+ continue;
778
+ }
779
+ while( db_step(&q)==SQLITE_ROW ){
780
+ cnt++;
781
+ bag_insert(&toCommit, db_column_int(&q, 0));
782
+ }
783
+ db_finalize(&q);
784
+ if( cnt==0 ){
673785
fossil_warning("fossil knows nothing about: %s", g.argv[ii]);
674786
result = 1;
675
- }else{
676
- g.aCommitFile[jj++] = iId;
677787
}
678
- blob_reset(&b);
788
+ blob_reset(&fname);
789
+ }
790
+ g.aCommitFile = fossil_malloc( (bag_count(&toCommit)+1) * sizeof(g.aCommitFile[0]) );
791
+ for(ii=bag_first(&toCommit); ii>0; ii=bag_next(&toCommit, ii)){
792
+ g.aCommitFile[jj++] = ii;
679793
}
680794
g.aCommitFile[jj] = 0;
795
+ bag_clear(&toCommit);
681796
}
682797
return result;
683798
}
684799
685800
/*
686801
--- src/checkin.c
+++ src/checkin.c
@@ -39,15 +39,36 @@
39 ){
40 Stmt q;
41 int nPrefix = strlen(zPrefix);
42 int nErr = 0;
43 Blob rewrittenPathname;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44 db_prepare(&q,
45 "SELECT pathname, deleted, chnged, rid, coalesce(origname!=pathname,0)"
46 " FROM vfile "
47 " WHERE is_selected(id)"
48 " AND (chnged OR deleted OR rid=0 OR pathname!=origname) ORDER BY 1"
 
49 );
50 blob_zero(&rewrittenPathname);
51 while( db_step(&q)==SQLITE_ROW ){
52 const char *zPathname = db_column_text(&q,0);
53 const char *zDisplayName = zPathname;
@@ -94,10 +115,12 @@
94 }else{
95 blob_appendf(report, "EDITED %s\n", zDisplayName);
96 }
97 }else if( isRenamed ){
98 blob_appendf(report, "RENAMED %s\n", zDisplayName);
 
 
99 }
100 free(zFullName);
101 }
102 blob_reset(&rewrittenPathname);
103 db_finalize(&q);
@@ -217,14 +240,15 @@
217 }
218
219 /*
220 ** COMMAND: ls
221 **
222 ** Usage: %fossil ls ?OPTIONS? ?VERSION?
223 **
224 ** Show the names of all files in the current checkout. The -v provides
225 ** extra information about each file.
 
226 **
227 ** Options:
228 ** --age Show when each file was committed
229 ** -v|--verbose Provide extra information about each file.
230 **
@@ -234,10 +258,13 @@
234 int vid;
235 Stmt q;
236 int verboseFlag;
237 int showAge;
238 char *zOrderBy = "pathname";
 
 
 
239
240 verboseFlag = find_option("verbose","v", 0)!=0;
241 if( !verboseFlag ){
242 verboseFlag = find_option("l","l", 0)!=0; /* deprecated */
243 }
@@ -250,25 +277,41 @@
250 }else{
251 zOrderBy = "mtime DESC";
252 }
253 }
254 verify_all_options();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255 vfile_check_signature(vid, 0);
256 if( showAge ){
257 db_prepare(&q,
258 "SELECT pathname, deleted, rid, chnged, coalesce(origname!=pathname,0),"
259 " datetime(checkin_mtime(%d,rid),'unixepoch','localtime')"
260 " FROM vfile"
261 " ORDER BY %s", vid, zOrderBy
262 );
263 }else{
264 db_prepare(&q,
265 "SELECT pathname, deleted, rid, chnged, coalesce(origname!=pathname,0)"
266 " FROM vfile"
267 " ORDER BY %s", zOrderBy
268 );
269 }
 
270 while( db_step(&q)==SQLITE_ROW ){
271 const char *zPathname = db_column_text(&q,0);
272 int isDeleted = db_column_int(&q, 1);
273 int isNew = db_column_int(&q,2)==0;
274 int chnged = db_column_int(&q,3);
@@ -297,17 +340,66 @@
297 }
298 free(zFullName);
299 }
300 db_finalize(&q);
301 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
303 /*
304 ** COMMAND: extras
305 ** Usage: %fossil extras ?OPTIONS?
306 **
307 ** Print a list of all files in the source tree that are not part of
308 ** the current checkout. See also the "clean" command.
 
309 **
310 ** Files and subdirectories whose names begin with "." are normally
311 ** ignored but can be included by adding the --dotfiles option.
312 **
313 ** The GLOBPATTERN is a comma-separated list of GLOB expressions for
@@ -326,13 +418,11 @@
326 ** directory.
327 **
328 ** See also: changes, clean, status
329 */
330 void extra_cmd(void){
331 Blob path;
332 Stmt q;
333 int n;
334 const char *zIgnoreFlag = find_option("ignore",0,1);
335 unsigned scanFlags = find_option("dotfiles",0,0)!=0 ? SCAN_ALL : 0;
336 int cwdRelative = 0;
337 Glob *pIgnore;
338 Blob rewrittenPathname;
@@ -340,19 +430,15 @@
340
341 if( find_option("temp",0,0)!=0 ) scanFlags |= SCAN_TEMP;
342 capture_case_sensitive_option();
343 db_must_be_within_tree();
344 cwdRelative = determine_cwd_relative_option();
345 db_multi_exec("CREATE TEMP TABLE sfile(x TEXT PRIMARY KEY %s)",
346 filename_collation());
347 n = strlen(g.zLocalRoot);
348 blob_init(&path, g.zLocalRoot, n-1);
349 if( zIgnoreFlag==0 ){
350 zIgnoreFlag = db_get("ignore-glob", 0);
351 }
352 pIgnore = glob_create(zIgnoreFlag);
353 vfile_scan(&path, blob_size(&path), scanFlags, pIgnore);
354 glob_free(pIgnore);
355 db_prepare(&q,
356 "SELECT x FROM sfile"
357 " WHERE x NOT IN (%s)"
358 " ORDER BY 1",
@@ -377,15 +463,16 @@
377 db_finalize(&q);
378 }
379
380 /*
381 ** COMMAND: clean
382 ** Usage: %fossil clean ?OPTIONS?
383 **
384 ** Delete all "extra" files in the source tree. "Extra" files are
385 ** files that are not officially part of the checkout. This operation
386 ** cannot be undone.
 
387 **
388 ** You will be prompted before removing each eligible file unless the
389 ** --force flag is in use or it matches the --clean option. The
390 ** GLOBPATTERN specified by the "ignore-glob" setting is used if the
391 ** --ignore option is omitted, the same with "clean-glob" and --clean
@@ -417,14 +504,14 @@
417 */
418 void clean_cmd(void){
419 int allFlag, dryRunFlag, verboseFlag;
420 unsigned scanFlags = 0;
421 const char *zIgnoreFlag, *zKeepFlag, *zCleanFlag;
422 Blob path, repo;
423 Stmt q;
424 int n;
425 Glob *pIgnore, *pKeep, *pClean;
 
426
427 dryRunFlag = find_option("dry-run","n",0)!=0;
428 if( !dryRunFlag ){
429 dryRunFlag = find_option("test",0,0)!=0; /* deprecated */
430 }
@@ -445,18 +532,14 @@
445 }
446 if( zCleanFlag==0 ){
447 zCleanFlag = db_get("clean-glob", 0);
448 }
449 verify_all_options();
450 db_multi_exec("CREATE TEMP TABLE sfile(x TEXT PRIMARY KEY %s)",
451 filename_collation());
452 n = strlen(g.zLocalRoot);
453 blob_init(&path, g.zLocalRoot, n-1);
454 pIgnore = glob_create(zIgnoreFlag);
455 pKeep = glob_create(zKeepFlag);
456 pClean = glob_create(zCleanFlag);
457 vfile_scan2(&path, blob_size(&path), scanFlags, pIgnore, pKeep);
458 glob_free(pKeep);
459 glob_free(pIgnore);
460 db_prepare(&q,
461 "SELECT %Q || x FROM sfile"
462 " WHERE x NOT IN (%s)"
@@ -465,17 +548,18 @@
465 );
466 if( file_tree_name(g.zRepositoryName, &repo, 0) ){
467 db_multi_exec("DELETE FROM sfile WHERE x=%B", &repo);
468 }
469 db_multi_exec("DELETE FROM sfile WHERE x IN (SELECT pathname FROM vfile)");
 
470 while( db_step(&q)==SQLITE_ROW ){
471 const char *zName = db_column_text(&q, 0);
472 if( !allFlag && !dryRunFlag && !glob_match(pClean, zName+n) ){
473 Blob ans;
474 char cReply;
475 char *prompt = mprintf("Remove unmanaged file \"%s\" (a=all/y/N)? ",
476 zName+n);
477 blob_zero(&ans);
478 prompt_user(prompt, &ans);
479 cReply = blob_str(&ans)[0];
480 if( cReply=='a' || cReply=='A' ){
481 allFlag = 1;
@@ -484,11 +568,11 @@
484 continue;
485 }
486 blob_reset(&ans);
487 }
488 if( verboseFlag || dryRunFlag ){
489 fossil_print("Removed unmanaged file: %s\n", zName+n);
490 }
491 if( !dryRunFlag ){
492 file_delete(zName);
493 }
494 }
@@ -657,29 +741,60 @@
657 **
658 ** Returns 1 if there was a warning, 0 otherwise.
659 */
660 int select_commit_files(void){
661 int result = 0;
 
662 if( g.argc>2 ){
663 int ii, jj=0;
664 Blob b;
665 blob_zero(&b);
666 g.aCommitFile = fossil_malloc(sizeof(int)*(g.argc-1));
 
 
667
 
 
 
668 for(ii=2; ii<g.argc; ii++){
669 int iId;
670 file_tree_name(g.argv[ii], &b, 1);
671 iId = db_int(-1, "SELECT id FROM vfile WHERE pathname=%Q", blob_str(&b));
672 if( iId<0 ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673 fossil_warning("fossil knows nothing about: %s", g.argv[ii]);
674 result = 1;
675 }else{
676 g.aCommitFile[jj++] = iId;
677 }
678 blob_reset(&b);
 
 
 
 
679 }
680 g.aCommitFile[jj] = 0;
 
681 }
682 return result;
683 }
684
685 /*
686
--- src/checkin.c
+++ src/checkin.c
@@ -39,15 +39,36 @@
39 ){
40 Stmt q;
41 int nPrefix = strlen(zPrefix);
42 int nErr = 0;
43 Blob rewrittenPathname;
44 Blob where;
45 const char *zName;
46 int i;
47
48 blob_zero(&where);
49 for(i=2; i<g.argc; i++) {
50 Blob fname;
51 file_tree_name(g.argv[i], &fname, 1);
52 zName = blob_str(&fname);
53 if( fossil_strcmp(zName, ".")==0 ) {
54 blob_reset(&where);
55 break;
56 }
57 blob_appendf(&where, " %s (pathname=%Q %s) "
58 "OR (pathname>'%q/' %s AND pathname<'%q0' %s)",
59 (blob_size(&where)>0) ? "OR" : "AND", zName,
60 filename_collation(), zName, filename_collation(),
61 zName, filename_collation());
62 }
63
64 db_prepare(&q,
65 "SELECT pathname, deleted, chnged, rid, coalesce(origname!=pathname,0)"
66 " FROM vfile "
67 " WHERE is_selected(id) %s"
68 " AND (chnged OR deleted OR rid=0 OR pathname!=origname) ORDER BY 1",
69 blob_str(&where)
70 );
71 blob_zero(&rewrittenPathname);
72 while( db_step(&q)==SQLITE_ROW ){
73 const char *zPathname = db_column_text(&q,0);
74 const char *zDisplayName = zPathname;
@@ -94,10 +115,12 @@
115 }else{
116 blob_appendf(report, "EDITED %s\n", zDisplayName);
117 }
118 }else if( isRenamed ){
119 blob_appendf(report, "RENAMED %s\n", zDisplayName);
120 }else{
121 report->nUsed -= nPrefix;
122 }
123 free(zFullName);
124 }
125 blob_reset(&rewrittenPathname);
126 db_finalize(&q);
@@ -217,14 +240,15 @@
240 }
241
242 /*
243 ** COMMAND: ls
244 **
245 ** Usage: %fossil ls ?OPTIONS? ?VERSION? ?FILENAMES?
246 **
247 ** Show the names of all files in the current checkout. The -v provides
248 ** extra information about each file. If FILENAMES are included, the only
249 ** the files listed (or their children if they are directories) are shown.
250 **
251 ** Options:
252 ** --age Show when each file was committed
253 ** -v|--verbose Provide extra information about each file.
254 **
@@ -234,10 +258,13 @@
258 int vid;
259 Stmt q;
260 int verboseFlag;
261 int showAge;
262 char *zOrderBy = "pathname";
263 Blob where;
264 int i;
265 const char *zName;
266
267 verboseFlag = find_option("verbose","v", 0)!=0;
268 if( !verboseFlag ){
269 verboseFlag = find_option("l","l", 0)!=0; /* deprecated */
270 }
@@ -250,25 +277,41 @@
277 }else{
278 zOrderBy = "mtime DESC";
279 }
280 }
281 verify_all_options();
282 blob_zero(&where);
283 for(i=2; i<g.argc; i++){
284 Blob fname;
285 file_tree_name(g.argv[i], &fname, 1);
286 zName = blob_str(&fname);
287 if( fossil_strcmp(zName, ".")==0 ) {
288 blob_reset(&where);
289 break;
290 }
291 blob_appendf(&where, " %s (pathname=%Q %s) "
292 "OR (pathname>'%q/' %s AND pathname<'%q0' %s)",
293 (blob_size(&where)>0) ? "OR" : "WHERE", zName,
294 filename_collation(), zName, filename_collation(),
295 zName, filename_collation());
296 }
297 vfile_check_signature(vid, 0);
298 if( showAge ){
299 db_prepare(&q,
300 "SELECT pathname, deleted, rid, chnged, coalesce(origname!=pathname,0),"
301 " datetime(checkin_mtime(%d,rid),'unixepoch','localtime')"
302 " FROM vfile %s"
303 " ORDER BY %s", vid, blob_str(&where), zOrderBy
304 );
305 }else{
306 db_prepare(&q,
307 "SELECT pathname, deleted, rid, chnged, coalesce(origname!=pathname,0)"
308 " FROM vfile %s"
309 " ORDER BY %s", blob_str(&where), zOrderBy
310 );
311 }
312 blob_reset(&where);
313 while( db_step(&q)==SQLITE_ROW ){
314 const char *zPathname = db_column_text(&q,0);
315 int isDeleted = db_column_int(&q, 1);
316 int isNew = db_column_int(&q,2)==0;
317 int chnged = db_column_int(&q,3);
@@ -297,17 +340,66 @@
340 }
341 free(zFullName);
342 }
343 db_finalize(&q);
344 }
345
346 /*
347 ** Create a TEMP table named SFILE and add all unmanaged files named on the command-line
348 ** to that table. If directories are named, then add all unmanaged files contained
349 ** underneath those directories. If there are no files or directories named on the
350 ** command-line, then add all unmanaged files anywhere in the checkout.
351 */
352 static void locate_unmanaged_files(
353 int argc, /* Number of command-line arguments to examine */
354 char **argv, /* values of command-line arguments */
355 unsigned scanFlags, /* Zero or more SCAN_xxx flags */
356 Glob *pIgnore1, /* Do not add files that match this GLOB */
357 Glob *pIgnore2 /* Omit files matching this GLOB too */
358 ){
359 Blob name; /* Name of a candidate file or directory */
360 char *zName; /* Name of a candidate file or directory */
361 int isDir; /* 1 for a directory, 0 if doesn't exist, 2 for anything else */
362 int i; /* Loop counter */
363 int nRoot; /* length of g.zLocalRoot */
364
365 db_multi_exec("CREATE TEMP TABLE sfile(x TEXT PRIMARY KEY %s)",
366 filename_collation());
367 nRoot = (int)strlen(g.zLocalRoot);
368 if( argc==0 ){
369 blob_init(&name, g.zLocalRoot, nRoot - 1);
370 vfile_scan(&name, blob_size(&name), scanFlags, pIgnore1, pIgnore2);
371 blob_reset(&name);
372 }else{
373 for(i=0; i<argc; i++){
374 file_canonical_name(argv[i], &name, 0);
375 zName = blob_str(&name);
376 isDir = file_wd_isdir(zName);
377 if( isDir==1 ){
378 vfile_scan(&name, nRoot-1, scanFlags, pIgnore1, pIgnore2);
379 }else if( isDir==0 ){
380 fossil_warning("not found: %s", &zName[nRoot]);
381 }else if( file_access(zName, R_OK) ){
382 fossil_fatal("cannot open %s", &zName[nRoot]);
383 }else{
384 db_multi_exec(
385 "INSERT OR IGNORE INTO sfile(x) VALUES(%Q)",
386 &zName[nRoot]
387 );
388 }
389 blob_reset(&name);
390 }
391 }
392 }
393
394 /*
395 ** COMMAND: extras
396 ** Usage: %fossil extras ?OPTIONS? ?PATH1 ...?
397 **
398 ** Print a list of all files in the source tree that are not part of
399 ** the current checkout. See also the "clean" command. If paths are
400 ** specified, only files in the given directories will be listed.
401 **
402 ** Files and subdirectories whose names begin with "." are normally
403 ** ignored but can be included by adding the --dotfiles option.
404 **
405 ** The GLOBPATTERN is a comma-separated list of GLOB expressions for
@@ -326,13 +418,11 @@
418 ** directory.
419 **
420 ** See also: changes, clean, status
421 */
422 void extra_cmd(void){
 
423 Stmt q;
 
424 const char *zIgnoreFlag = find_option("ignore",0,1);
425 unsigned scanFlags = find_option("dotfiles",0,0)!=0 ? SCAN_ALL : 0;
426 int cwdRelative = 0;
427 Glob *pIgnore;
428 Blob rewrittenPathname;
@@ -340,19 +430,15 @@
430
431 if( find_option("temp",0,0)!=0 ) scanFlags |= SCAN_TEMP;
432 capture_case_sensitive_option();
433 db_must_be_within_tree();
434 cwdRelative = determine_cwd_relative_option();
 
 
 
 
435 if( zIgnoreFlag==0 ){
436 zIgnoreFlag = db_get("ignore-glob", 0);
437 }
438 pIgnore = glob_create(zIgnoreFlag);
439 locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore, 0);
440 glob_free(pIgnore);
441 db_prepare(&q,
442 "SELECT x FROM sfile"
443 " WHERE x NOT IN (%s)"
444 " ORDER BY 1",
@@ -377,15 +463,16 @@
463 db_finalize(&q);
464 }
465
466 /*
467 ** COMMAND: clean
468 ** Usage: %fossil clean ?OPTIONS? ?PATH1 ...?
469 **
470 ** Delete all "extra" files in the source tree. "Extra" files are
471 ** files that are not officially part of the checkout. This operation
472 ** cannot be undone. If paths are specified, only the directories or
473 ** files specified will be considered for cleaning.
474 **
475 ** You will be prompted before removing each eligible file unless the
476 ** --force flag is in use or it matches the --clean option. The
477 ** GLOBPATTERN specified by the "ignore-glob" setting is used if the
478 ** --ignore option is omitted, the same with "clean-glob" and --clean
@@ -417,14 +504,14 @@
504 */
505 void clean_cmd(void){
506 int allFlag, dryRunFlag, verboseFlag;
507 unsigned scanFlags = 0;
508 const char *zIgnoreFlag, *zKeepFlag, *zCleanFlag;
509 Blob repo;
510 Stmt q;
 
511 Glob *pIgnore, *pKeep, *pClean;
512 int nRoot;
513
514 dryRunFlag = find_option("dry-run","n",0)!=0;
515 if( !dryRunFlag ){
516 dryRunFlag = find_option("test",0,0)!=0; /* deprecated */
517 }
@@ -445,18 +532,14 @@
532 }
533 if( zCleanFlag==0 ){
534 zCleanFlag = db_get("clean-glob", 0);
535 }
536 verify_all_options();
 
 
 
 
537 pIgnore = glob_create(zIgnoreFlag);
538 pKeep = glob_create(zKeepFlag);
539 pClean = glob_create(zCleanFlag);
540 locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore, pKeep);
541 glob_free(pKeep);
542 glob_free(pIgnore);
543 db_prepare(&q,
544 "SELECT %Q || x FROM sfile"
545 " WHERE x NOT IN (%s)"
@@ -465,17 +548,18 @@
548 );
549 if( file_tree_name(g.zRepositoryName, &repo, 0) ){
550 db_multi_exec("DELETE FROM sfile WHERE x=%B", &repo);
551 }
552 db_multi_exec("DELETE FROM sfile WHERE x IN (SELECT pathname FROM vfile)");
553 nRoot = (int)strlen(g.zLocalRoot);
554 while( db_step(&q)==SQLITE_ROW ){
555 const char *zName = db_column_text(&q, 0);
556 if( !allFlag && !dryRunFlag && !glob_match(pClean, zName+nRoot) ){
557 Blob ans;
558 char cReply;
559 char *prompt = mprintf("Remove unmanaged file \"%s\" (a=all/y/N)? ",
560 zName+nRoot);
561 blob_zero(&ans);
562 prompt_user(prompt, &ans);
563 cReply = blob_str(&ans)[0];
564 if( cReply=='a' || cReply=='A' ){
565 allFlag = 1;
@@ -484,11 +568,11 @@
568 continue;
569 }
570 blob_reset(&ans);
571 }
572 if( verboseFlag || dryRunFlag ){
573 fossil_print("Removed unmanaged file: %s\n", zName+nRoot);
574 }
575 if( !dryRunFlag ){
576 file_delete(zName);
577 }
578 }
@@ -657,29 +741,60 @@
741 **
742 ** Returns 1 if there was a warning, 0 otherwise.
743 */
744 int select_commit_files(void){
745 int result = 0;
746 assert( g.aCommitFile==0 );
747 if( g.argc>2 ){
748 int ii, jj=0;
749 Blob fname;
750 int isDir;
751 Stmt q;
752 const char *zCollate;
753 Bag toCommit;
754
755 zCollate = filename_collation();
756 blob_zero(&fname);
757 bag_init(&toCommit);
758 for(ii=2; ii<g.argc; ii++){
759 int cnt = 0;
760 file_tree_name(g.argv[ii], &fname, 1);
761 if( fossil_strcmp(blob_str(&fname),".")==0 ){
762 bag_clear(&toCommit);
763 return result;
764 }
765 isDir = file_isdir(g.argv[ii]);
766 if( isDir==1 ){
767 db_prepare(&q,
768 "SELECT id FROM vfile WHERE pathname>'%q/' %s AND pathname<'%q0'",
769 blob_str(&fname), zCollate, blob_str(&fname), zCollate);
770 }else if( isDir==2 ){
771 db_prepare(&q,
772 "SELECT id FROM vfile WHERE pathname=%Q",
773 blob_str(&fname), zCollate);
774 }else{
775 fossil_warning("not found: %s", g.argv[ii]);
776 result = 1;
777 continue;
778 }
779 while( db_step(&q)==SQLITE_ROW ){
780 cnt++;
781 bag_insert(&toCommit, db_column_int(&q, 0));
782 }
783 db_finalize(&q);
784 if( cnt==0 ){
785 fossil_warning("fossil knows nothing about: %s", g.argv[ii]);
786 result = 1;
 
 
787 }
788 blob_reset(&fname);
789 }
790 g.aCommitFile = fossil_malloc( (bag_count(&toCommit)+1) * sizeof(g.aCommitFile[0]) );
791 for(ii=bag_first(&toCommit); ii>0; ii=bag_next(&toCommit, ii)){
792 g.aCommitFile[jj++] = ii;
793 }
794 g.aCommitFile[jj] = 0;
795 bag_clear(&toCommit);
796 }
797 return result;
798 }
799
800 /*
801
+8 -1
--- src/checkout.c
+++ src/checkout.c
@@ -278,11 +278,11 @@
278278
**
279279
** Usage: %fossil close ?OPTIONS?
280280
**
281281
** The opposite of "open". Close the current database connection.
282282
** Require a -f or --force flag if there are unsaved changed in the
283
-** current check-out.
283
+** current check-out or if there is non-empty stash.
284284
**
285285
** Options:
286286
** --force|-f necessary to close a check out with uncommitted changes
287287
**
288288
** See also: open
@@ -291,12 +291,19 @@
291291
int forceFlag = find_option("force","f",0)!=0;
292292
db_must_be_within_tree();
293293
if( !forceFlag && unsaved_changes()==1 ){
294294
fossil_fatal("there are unsaved changes in the current checkout");
295295
}
296
+ if( !forceFlag
297
+ && db_exists("SELECT 1 FROM %s.sqlite_master WHERE name='stash'",
298
+ db_name("localdb"))
299
+ && db_exists("SELECT 1 FROM %s.stash", db_name("localdb"))
300
+ ){
301
+ fossil_fatal("closing the checkout will delete your stash");
302
+ }
296303
if( db_is_writeable("repository") ){
297304
db_multi_exec("DELETE FROM config WHERE name='ckout:%q'", g.zLocalRoot);
298305
}
299306
unlink_local_database(1);
300307
db_close(1);
301308
unlink_local_database(0);
302309
}
303310
--- src/checkout.c
+++ src/checkout.c
@@ -278,11 +278,11 @@
278 **
279 ** Usage: %fossil close ?OPTIONS?
280 **
281 ** The opposite of "open". Close the current database connection.
282 ** Require a -f or --force flag if there are unsaved changed in the
283 ** current check-out.
284 **
285 ** Options:
286 ** --force|-f necessary to close a check out with uncommitted changes
287 **
288 ** See also: open
@@ -291,12 +291,19 @@
291 int forceFlag = find_option("force","f",0)!=0;
292 db_must_be_within_tree();
293 if( !forceFlag && unsaved_changes()==1 ){
294 fossil_fatal("there are unsaved changes in the current checkout");
295 }
 
 
 
 
 
 
 
296 if( db_is_writeable("repository") ){
297 db_multi_exec("DELETE FROM config WHERE name='ckout:%q'", g.zLocalRoot);
298 }
299 unlink_local_database(1);
300 db_close(1);
301 unlink_local_database(0);
302 }
303
--- src/checkout.c
+++ src/checkout.c
@@ -278,11 +278,11 @@
278 **
279 ** Usage: %fossil close ?OPTIONS?
280 **
281 ** The opposite of "open". Close the current database connection.
282 ** Require a -f or --force flag if there are unsaved changed in the
283 ** current check-out or if there is non-empty stash.
284 **
285 ** Options:
286 ** --force|-f necessary to close a check out with uncommitted changes
287 **
288 ** See also: open
@@ -291,12 +291,19 @@
291 int forceFlag = find_option("force","f",0)!=0;
292 db_must_be_within_tree();
293 if( !forceFlag && unsaved_changes()==1 ){
294 fossil_fatal("there are unsaved changes in the current checkout");
295 }
296 if( !forceFlag
297 && db_exists("SELECT 1 FROM %s.sqlite_master WHERE name='stash'",
298 db_name("localdb"))
299 && db_exists("SELECT 1 FROM %s.stash", db_name("localdb"))
300 ){
301 fossil_fatal("closing the checkout will delete your stash");
302 }
303 if( db_is_writeable("repository") ){
304 db_multi_exec("DELETE FROM config WHERE name='ckout:%q'", g.zLocalRoot);
305 }
306 unlink_local_database(1);
307 db_close(1);
308 unlink_local_database(0);
309 }
310
--- src/cson_amalgamation.c
+++ src/cson_amalgamation.c
@@ -26,11 +26,15 @@
2626
#else
2727
# define JSON_PARSER_DLL_API
2828
#endif
2929
3030
/* Determine the integer type use to parse non-floating point numbers */
31
-#if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG == 1
31
+#ifdef _WIN32
32
+typedef __int64 JSON_int_t;
33
+#define JSON_PARSER_INTEGER_SSCANF_TOKEN "%I64d"
34
+#define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%I64d"
35
+#elif (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
3236
typedef long long JSON_int_t;
3337
#define JSON_PARSER_INTEGER_SSCANF_TOKEN "%lld"
3438
#define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%lld"
3539
#else
3640
typedef long JSON_int_t;
3741
--- src/cson_amalgamation.c
+++ src/cson_amalgamation.c
@@ -26,11 +26,15 @@
26 #else
27 # define JSON_PARSER_DLL_API
28 #endif
29
30 /* Determine the integer type use to parse non-floating point numbers */
31 #if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG == 1
 
 
 
 
32 typedef long long JSON_int_t;
33 #define JSON_PARSER_INTEGER_SSCANF_TOKEN "%lld"
34 #define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%lld"
35 #else
36 typedef long JSON_int_t;
37
--- src/cson_amalgamation.c
+++ src/cson_amalgamation.c
@@ -26,11 +26,15 @@
26 #else
27 # define JSON_PARSER_DLL_API
28 #endif
29
30 /* Determine the integer type use to parse non-floating point numbers */
31 #ifdef _WIN32
32 typedef __int64 JSON_int_t;
33 #define JSON_PARSER_INTEGER_SSCANF_TOKEN "%I64d"
34 #define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%I64d"
35 #elif (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
36 typedef long long JSON_int_t;
37 #define JSON_PARSER_INTEGER_SSCANF_TOKEN "%lld"
38 #define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%lld"
39 #else
40 typedef long JSON_int_t;
41
--- src/cson_amalgamation.h
+++ src/cson_amalgamation.h
@@ -51,11 +51,15 @@
5151
/** @typedef some_long_int_type cson_int_t
5252
5353
Typedef for JSON-like integer types. This is (long long) where feasible,
5454
otherwise (long).
5555
*/
56
-#if (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
56
+#ifdef _WIN32
57
+typedef __int64 cson_int_t;
58
+#define CSON_INT_T_SFMT "I64d"
59
+#define CSON_INT_T_PFMT "I64d"
60
+#elif (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
5761
typedef long long cson_int_t;
5862
#define CSON_INT_T_SFMT "lld"
5963
#define CSON_INT_T_PFMT "lld"
6064
#else
6165
typedef long cson_int_t;
6266
--- src/cson_amalgamation.h
+++ src/cson_amalgamation.h
@@ -51,11 +51,15 @@
51 /** @typedef some_long_int_type cson_int_t
52
53 Typedef for JSON-like integer types. This is (long long) where feasible,
54 otherwise (long).
55 */
56 #if (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
 
 
 
 
57 typedef long long cson_int_t;
58 #define CSON_INT_T_SFMT "lld"
59 #define CSON_INT_T_PFMT "lld"
60 #else
61 typedef long cson_int_t;
62
--- src/cson_amalgamation.h
+++ src/cson_amalgamation.h
@@ -51,11 +51,15 @@
51 /** @typedef some_long_int_type cson_int_t
52
53 Typedef for JSON-like integer types. This is (long long) where feasible,
54 otherwise (long).
55 */
56 #ifdef _WIN32
57 typedef __int64 cson_int_t;
58 #define CSON_INT_T_SFMT "I64d"
59 #define CSON_INT_T_PFMT "I64d"
60 #elif (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
61 typedef long long cson_int_t;
62 #define CSON_INT_T_SFMT "lld"
63 #define CSON_INT_T_PFMT "lld"
64 #else
65 typedef long cson_int_t;
66
+6 -2
--- src/db.c
+++ src/db.c
@@ -399,12 +399,16 @@
399399
}
400400
401401
/*
402402
** Return the rowid of the most recent insert
403403
*/
404
-i64 db_last_insert_rowid(void){
405
- return sqlite3_last_insert_rowid(g.db);
404
+int db_last_insert_rowid(void){
405
+ i64 x = sqlite3_last_insert_rowid(g.db);
406
+ if( x<0 || x>(i64)2147483647 ){
407
+ fossil_fatal("rowid out of range (0..2147483647)");
408
+ }
409
+ return (int)x;
406410
}
407411
408412
/*
409413
** Return the number of rows that were changed by the most recent
410414
** INSERT, UPDATE, or DELETE. Auxiliary changes caused by triggers
411415
--- src/db.c
+++ src/db.c
@@ -399,12 +399,16 @@
399 }
400
401 /*
402 ** Return the rowid of the most recent insert
403 */
404 i64 db_last_insert_rowid(void){
405 return sqlite3_last_insert_rowid(g.db);
 
 
 
 
406 }
407
408 /*
409 ** Return the number of rows that were changed by the most recent
410 ** INSERT, UPDATE, or DELETE. Auxiliary changes caused by triggers
411
--- src/db.c
+++ src/db.c
@@ -399,12 +399,16 @@
399 }
400
401 /*
402 ** Return the rowid of the most recent insert
403 */
404 int db_last_insert_rowid(void){
405 i64 x = sqlite3_last_insert_rowid(g.db);
406 if( x<0 || x>(i64)2147483647 ){
407 fossil_fatal("rowid out of range (0..2147483647)");
408 }
409 return (int)x;
410 }
411
412 /*
413 ** Return the number of rows that were changed by the most recent
414 ** INSERT, UPDATE, or DELETE. Auxiliary changes caused by triggers
415
--- src/diffcmd.c
+++ src/diffcmd.c
@@ -602,10 +602,11 @@
602602
static const char zDiffScript[] =
603603
@ package require Tk
604604
@ wm withdraw .
605605
@ wm title . {Fossil Diff}
606606
@ wm iconname . {Fossil Diff}
607
+@ bind . <q> exit
607608
@ set body {}
608609
@ set mx 80 ;# Length of the longest line of text
609610
@ set nLine 0 ;# Number of lines of text
610611
@ text .t -width 180 -yscroll {.sb set}
611612
@ if {$tcl_platform(platform)=="windows"} {.t config -font {courier 9}}
612613
--- src/diffcmd.c
+++ src/diffcmd.c
@@ -602,10 +602,11 @@
602 static const char zDiffScript[] =
603 @ package require Tk
604 @ wm withdraw .
605 @ wm title . {Fossil Diff}
606 @ wm iconname . {Fossil Diff}
 
607 @ set body {}
608 @ set mx 80 ;# Length of the longest line of text
609 @ set nLine 0 ;# Number of lines of text
610 @ text .t -width 180 -yscroll {.sb set}
611 @ if {$tcl_platform(platform)=="windows"} {.t config -font {courier 9}}
612
--- src/diffcmd.c
+++ src/diffcmd.c
@@ -602,10 +602,11 @@
602 static const char zDiffScript[] =
603 @ package require Tk
604 @ wm withdraw .
605 @ wm title . {Fossil Diff}
606 @ wm iconname . {Fossil Diff}
607 @ bind . <q> exit
608 @ set body {}
609 @ set mx 80 ;# Length of the longest line of text
610 @ set nLine 0 ;# Number of lines of text
611 @ text .t -width 180 -yscroll {.sb set}
612 @ if {$tcl_platform(platform)=="windows"} {.t config -font {courier 9}}
613
+1
--- src/doc.c
+++ src/doc.c
@@ -181,10 +181,11 @@
181181
{ "mkd", 3, "text/x-markdown" },
182182
{ "mov", 3, "video/quicktime" },
183183
{ "movie", 5, "video/x-sgi-movie" },
184184
{ "mp2", 3, "audio/mpeg" },
185185
{ "mp3", 3, "audio/mpeg" },
186
+ { "mp4", 3, "video/mp4" },
186187
{ "mpe", 3, "video/mpeg" },
187188
{ "mpeg", 4, "video/mpeg" },
188189
{ "mpg", 3, "video/mpeg" },
189190
{ "mpga", 4, "audio/mpeg" },
190191
{ "ms", 2, "application/x-troff-ms" },
191192
--- src/doc.c
+++ src/doc.c
@@ -181,10 +181,11 @@
181 { "mkd", 3, "text/x-markdown" },
182 { "mov", 3, "video/quicktime" },
183 { "movie", 5, "video/x-sgi-movie" },
184 { "mp2", 3, "audio/mpeg" },
185 { "mp3", 3, "audio/mpeg" },
 
186 { "mpe", 3, "video/mpeg" },
187 { "mpeg", 4, "video/mpeg" },
188 { "mpg", 3, "video/mpeg" },
189 { "mpga", 4, "audio/mpeg" },
190 { "ms", 2, "application/x-troff-ms" },
191
--- src/doc.c
+++ src/doc.c
@@ -181,10 +181,11 @@
181 { "mkd", 3, "text/x-markdown" },
182 { "mov", 3, "video/quicktime" },
183 { "movie", 5, "video/x-sgi-movie" },
184 { "mp2", 3, "audio/mpeg" },
185 { "mp3", 3, "audio/mpeg" },
186 { "mp4", 3, "video/mp4" },
187 { "mpe", 3, "video/mpeg" },
188 { "mpeg", 4, "video/mpeg" },
189 { "mpg", 3, "video/mpeg" },
190 { "mpga", 4, "audio/mpeg" },
191 { "ms", 2, "application/x-troff-ms" },
192
--- src/http_socket.c
+++ src/http_socket.c
@@ -200,11 +200,12 @@
200200
*/
201201
size_t socket_receive(void *NotUsed, void *pContent, size_t N){
202202
ssize_t got;
203203
size_t total = 0;
204204
while( N>0 ){
205
- got = recv(iSocket, pContent, N, 0);
205
+ /* WinXP fails for large values of N. So limit it to 64KiB. */
206
+ got = recv(iSocket, pContent, N>65536 ? 65536 : N, 0);
206207
if( got<=0 ) break;
207208
total += (size_t)got;
208209
N -= (size_t)got;
209210
pContent = (void*)&((char*)pContent)[got];
210211
}
211212
--- src/http_socket.c
+++ src/http_socket.c
@@ -200,11 +200,12 @@
200 */
201 size_t socket_receive(void *NotUsed, void *pContent, size_t N){
202 ssize_t got;
203 size_t total = 0;
204 while( N>0 ){
205 got = recv(iSocket, pContent, N, 0);
 
206 if( got<=0 ) break;
207 total += (size_t)got;
208 N -= (size_t)got;
209 pContent = (void*)&((char*)pContent)[got];
210 }
211
--- src/http_socket.c
+++ src/http_socket.c
@@ -200,11 +200,12 @@
200 */
201 size_t socket_receive(void *NotUsed, void *pContent, size_t N){
202 ssize_t got;
203 size_t total = 0;
204 while( N>0 ){
205 /* WinXP fails for large values of N. So limit it to 64KiB. */
206 got = recv(iSocket, pContent, N>65536 ? 65536 : N, 0);
207 if( got<=0 ) break;
208 total += (size_t)got;
209 N -= (size_t)got;
210 pContent = (void*)&((char*)pContent)[got];
211 }
212
+1 -1
--- src/json.c
+++ src/json.c
@@ -267,11 +267,11 @@
267267
v = cson_value_new_string(zStr, strlen(zStr));
268268
free(zStr);
269269
return v;
270270
}
271271
272
-cson_value * json_new_int( int v ){
272
+cson_value * json_new_int( i64 v ){
273273
return cson_value_new_integer((cson_int_t)v);
274274
}
275275
276276
/*
277277
** Gets a POST/POST.payload/GET/COOKIE/ENV value. The returned memory
278278
--- src/json.c
+++ src/json.c
@@ -267,11 +267,11 @@
267 v = cson_value_new_string(zStr, strlen(zStr));
268 free(zStr);
269 return v;
270 }
271
272 cson_value * json_new_int( int v ){
273 return cson_value_new_integer((cson_int_t)v);
274 }
275
276 /*
277 ** Gets a POST/POST.payload/GET/COOKIE/ENV value. The returned memory
278
--- src/json.c
+++ src/json.c
@@ -267,11 +267,11 @@
267 v = cson_value_new_string(zStr, strlen(zStr));
268 free(zStr);
269 return v;
270 }
271
272 cson_value * json_new_int( i64 v ){
273 return cson_value_new_integer((cson_int_t)v);
274 }
275
276 /*
277 ** Gets a POST/POST.payload/GET/COOKIE/ENV value. The returned memory
278
--- src/json_artifact.c
+++ src/json_artifact.c
@@ -110,21 +110,21 @@
110110
cson_value * tmpV = NULL;
111111
const char *zUuid = db_column_text(&q, 0);
112112
const char *zUser;
113113
const char *zComment;
114114
char * zEUser, * zEComment;
115
- int mtime, omtime;
115
+ i64 mtime, omtime;
116116
v = cson_value_new_object();
117117
o = cson_value_get_object(v);
118118
#define SET(K,V) cson_object_set(o,(K), (V))
119119
SET("type", eventTypeLabel );
120120
SET("uuid",json_new_string(zUuid));
121121
SET("isLeaf", cson_value_new_bool(is_a_leaf(rid)));
122122
123
- mtime = db_column_int(&q,1);
123
+ mtime = db_column_int64(&q,1);
124124
SET("timestamp",json_new_int(mtime));
125
- omtime = db_column_int(&q,2);
125
+ omtime = db_column_int64(&q,2);
126126
if(omtime && (omtime!=mtime)){
127127
SET("originTime",json_new_int(omtime));
128128
}
129129
130130
zUser = db_column_text(&q,3);
131131
--- src/json_artifact.c
+++ src/json_artifact.c
@@ -110,21 +110,21 @@
110 cson_value * tmpV = NULL;
111 const char *zUuid = db_column_text(&q, 0);
112 const char *zUser;
113 const char *zComment;
114 char * zEUser, * zEComment;
115 int mtime, omtime;
116 v = cson_value_new_object();
117 o = cson_value_get_object(v);
118 #define SET(K,V) cson_object_set(o,(K), (V))
119 SET("type", eventTypeLabel );
120 SET("uuid",json_new_string(zUuid));
121 SET("isLeaf", cson_value_new_bool(is_a_leaf(rid)));
122
123 mtime = db_column_int(&q,1);
124 SET("timestamp",json_new_int(mtime));
125 omtime = db_column_int(&q,2);
126 if(omtime && (omtime!=mtime)){
127 SET("originTime",json_new_int(omtime));
128 }
129
130 zUser = db_column_text(&q,3);
131
--- src/json_artifact.c
+++ src/json_artifact.c
@@ -110,21 +110,21 @@
110 cson_value * tmpV = NULL;
111 const char *zUuid = db_column_text(&q, 0);
112 const char *zUser;
113 const char *zComment;
114 char * zEUser, * zEComment;
115 i64 mtime, omtime;
116 v = cson_value_new_object();
117 o = cson_value_get_object(v);
118 #define SET(K,V) cson_object_set(o,(K), (V))
119 SET("type", eventTypeLabel );
120 SET("uuid",json_new_string(zUuid));
121 SET("isLeaf", cson_value_new_bool(is_a_leaf(rid)));
122
123 mtime = db_column_int64(&q,1);
124 SET("timestamp",json_new_int(mtime));
125 omtime = db_column_int64(&q,2);
126 if(omtime && (omtime!=mtime)){
127 SET("originTime",json_new_int(omtime));
128 }
129
130 zUser = db_column_text(&q,3);
131
--- src/json_finfo.c
+++ src/json_finfo.c
@@ -125,15 +125,15 @@
125125
int const isDel = db_column_int(&q,10);
126126
cson_array_append( checkins, cson_object_value(row) );
127127
cson_object_set(row, "checkin", json_new_string( db_column_text(&q,1) ));
128128
cson_object_set(row, "uuid", json_new_string( db_column_text(&q,2) ));
129129
/*cson_object_set(row, "parentArtifact", json_new_string( db_column_text(&q,6) ));*/
130
- cson_object_set(row, "timestamp", json_new_int( db_column_int(&q,3) ));
130
+ cson_object_set(row, "timestamp", json_new_int( db_column_int64(&q,3) ));
131131
cson_object_set(row, "user", json_new_string( db_column_text(&q,4) ));
132132
cson_object_set(row, "comment", json_new_string( db_column_text(&q,5) ));
133133
/*cson_object_set(row, "bgColor", json_new_string( db_column_text(&q,7) ));*/
134
- cson_object_set(row, "size", cson_value_new_integer( (cson_int_t)db_column_int64(&q,8) ));
134
+ cson_object_set(row, "size", json_new_int( db_column_int64(&q,8) ));
135135
cson_object_set(row, "state",
136136
json_new_string(json_artifact_status_to_string(isNew,isDel)));
137137
if( (0 < limit) && (++currentRow >= limit) ){
138138
break;
139139
}
140140
--- src/json_finfo.c
+++ src/json_finfo.c
@@ -125,15 +125,15 @@
125 int const isDel = db_column_int(&q,10);
126 cson_array_append( checkins, cson_object_value(row) );
127 cson_object_set(row, "checkin", json_new_string( db_column_text(&q,1) ));
128 cson_object_set(row, "uuid", json_new_string( db_column_text(&q,2) ));
129 /*cson_object_set(row, "parentArtifact", json_new_string( db_column_text(&q,6) ));*/
130 cson_object_set(row, "timestamp", json_new_int( db_column_int(&q,3) ));
131 cson_object_set(row, "user", json_new_string( db_column_text(&q,4) ));
132 cson_object_set(row, "comment", json_new_string( db_column_text(&q,5) ));
133 /*cson_object_set(row, "bgColor", json_new_string( db_column_text(&q,7) ));*/
134 cson_object_set(row, "size", cson_value_new_integer( (cson_int_t)db_column_int64(&q,8) ));
135 cson_object_set(row, "state",
136 json_new_string(json_artifact_status_to_string(isNew,isDel)));
137 if( (0 < limit) && (++currentRow >= limit) ){
138 break;
139 }
140
--- src/json_finfo.c
+++ src/json_finfo.c
@@ -125,15 +125,15 @@
125 int const isDel = db_column_int(&q,10);
126 cson_array_append( checkins, cson_object_value(row) );
127 cson_object_set(row, "checkin", json_new_string( db_column_text(&q,1) ));
128 cson_object_set(row, "uuid", json_new_string( db_column_text(&q,2) ));
129 /*cson_object_set(row, "parentArtifact", json_new_string( db_column_text(&q,6) ));*/
130 cson_object_set(row, "timestamp", json_new_int( db_column_int64(&q,3) ));
131 cson_object_set(row, "user", json_new_string( db_column_text(&q,4) ));
132 cson_object_set(row, "comment", json_new_string( db_column_text(&q,5) ));
133 /*cson_object_set(row, "bgColor", json_new_string( db_column_text(&q,7) ));*/
134 cson_object_set(row, "size", json_new_int( db_column_int64(&q,8) ));
135 cson_object_set(row, "state",
136 json_new_string(json_artifact_status_to_string(isNew,isDel)));
137 if( (0 < limit) && (++currentRow >= limit) ){
138 break;
139 }
140
+11 -18
--- src/main.c
+++ src/main.c
@@ -785,34 +785,26 @@
785785
fossil_print("This is fossil version " RELEASE_VERSION " "
786786
MANIFEST_VERSION " " MANIFEST_DATE " UTC\n");
787787
if(!find_option("verbose","v",0)){
788788
return;
789789
}else{
790
- int count = 0;
791
- fossil_print("\nCompiled using \"%s\" with\nSQLite %s [%s],\nzlib %s, "
792
- "and the following optional features enabled:\n\n",
793
- COMPILER_NAME, SQLITE_VERSION, SQLITE_SOURCE_ID,
794
- ZLIB_VERSION);
790
+ fossil_print("Compiled on %s %s using %s (%d-bit)\n",
791
+ __DATE__, __TIME__, COMPILER_NAME, sizeof(void*)*8);
792
+ fossil_print("SQLite %s %.30s\n", SQLITE_VERSION, SQLITE_SOURCE_ID);
793
+ fossil_print("zlib %s\n", ZLIB_VERSION);
795794
#if defined(FOSSIL_ENABLE_SSL)
796
- ++count;
797
- fossil_print("\tSSL (%s)\n", OPENSSL_VERSION_TEXT);
795
+ fossil_print("SSL (%s)\n", OPENSSL_VERSION_TEXT);
798796
#endif
799797
#if defined(FOSSIL_ENABLE_TCL)
800
- ++count;
801
- fossil_print("\tTCL (Tcl %s)\n", TCL_PATCH_LEVEL);
798
+ fossil_print("TCL (Tcl %s)\n", TCL_PATCH_LEVEL);
802799
#endif
803800
#if defined(FOSSIL_ENABLE_TCL_STUBS)
804
- ++count;
805
- fossil_print("\tTCL_STUBS\n");
801
+ fossil_print("TCL_STUBS\n");
806802
#endif
807803
#if defined(FOSSIL_ENABLE_JSON)
808
- ++count;
809
- fossil_print("\tJSON (API %s)\n", FOSSIL_JSON_API_VERSION);
804
+ fossil_print("JSON (API %s)\n", FOSSIL_JSON_API_VERSION);
810805
#endif
811
- if( !count ){
812
- fossil_print("\tNo optional features were enabled.\n");
813
- }
814806
}
815807
}
816808
817809
818810
/*
@@ -1811,18 +1803,19 @@
18111803
zPort = find_option("port", "P", 1);
18121804
zNotFound = find_option("notfound", 0, 1);
18131805
zAltBase = find_option("baseurl", 0, 1);
18141806
if( zAltBase ){
18151807
set_base_url(zAltBase);
1808
+ }
1809
+ if ( find_option("localhost", 0, 0)!=0 ){
1810
+ flags |= HTTP_SERVER_LOCALHOST;
18161811
}
18171812
if( g.argc!=2 && g.argc!=3 ) usage("?REPOSITORY?");
18181813
isUiCmd = g.argv[1][0]=='u';
18191814
if( isUiCmd ){
18201815
flags |= HTTP_SERVER_LOCALHOST;
18211816
g.useLocalauth = 1;
1822
- }else if ( find_option("localhost", 0, 0)!=0 ){
1823
- flags |= HTTP_SERVER_LOCALHOST;
18241817
}
18251818
find_server_repository(isUiCmd && zNotFound==0);
18261819
if( zPort ){
18271820
int i;
18281821
for(i=strlen(zPort)-1; i>=0 && zPort[i]!=':'; i--){}
18291822
--- src/main.c
+++ src/main.c
@@ -785,34 +785,26 @@
785 fossil_print("This is fossil version " RELEASE_VERSION " "
786 MANIFEST_VERSION " " MANIFEST_DATE " UTC\n");
787 if(!find_option("verbose","v",0)){
788 return;
789 }else{
790 int count = 0;
791 fossil_print("\nCompiled using \"%s\" with\nSQLite %s [%s],\nzlib %s, "
792 "and the following optional features enabled:\n\n",
793 COMPILER_NAME, SQLITE_VERSION, SQLITE_SOURCE_ID,
794 ZLIB_VERSION);
795 #if defined(FOSSIL_ENABLE_SSL)
796 ++count;
797 fossil_print("\tSSL (%s)\n", OPENSSL_VERSION_TEXT);
798 #endif
799 #if defined(FOSSIL_ENABLE_TCL)
800 ++count;
801 fossil_print("\tTCL (Tcl %s)\n", TCL_PATCH_LEVEL);
802 #endif
803 #if defined(FOSSIL_ENABLE_TCL_STUBS)
804 ++count;
805 fossil_print("\tTCL_STUBS\n");
806 #endif
807 #if defined(FOSSIL_ENABLE_JSON)
808 ++count;
809 fossil_print("\tJSON (API %s)\n", FOSSIL_JSON_API_VERSION);
810 #endif
811 if( !count ){
812 fossil_print("\tNo optional features were enabled.\n");
813 }
814 }
815 }
816
817
818 /*
@@ -1811,18 +1803,19 @@
1811 zPort = find_option("port", "P", 1);
1812 zNotFound = find_option("notfound", 0, 1);
1813 zAltBase = find_option("baseurl", 0, 1);
1814 if( zAltBase ){
1815 set_base_url(zAltBase);
 
 
 
1816 }
1817 if( g.argc!=2 && g.argc!=3 ) usage("?REPOSITORY?");
1818 isUiCmd = g.argv[1][0]=='u';
1819 if( isUiCmd ){
1820 flags |= HTTP_SERVER_LOCALHOST;
1821 g.useLocalauth = 1;
1822 }else if ( find_option("localhost", 0, 0)!=0 ){
1823 flags |= HTTP_SERVER_LOCALHOST;
1824 }
1825 find_server_repository(isUiCmd && zNotFound==0);
1826 if( zPort ){
1827 int i;
1828 for(i=strlen(zPort)-1; i>=0 && zPort[i]!=':'; i--){}
1829
--- src/main.c
+++ src/main.c
@@ -785,34 +785,26 @@
785 fossil_print("This is fossil version " RELEASE_VERSION " "
786 MANIFEST_VERSION " " MANIFEST_DATE " UTC\n");
787 if(!find_option("verbose","v",0)){
788 return;
789 }else{
790 fossil_print("Compiled on %s %s using %s (%d-bit)\n",
791 __DATE__, __TIME__, COMPILER_NAME, sizeof(void*)*8);
792 fossil_print("SQLite %s %.30s\n", SQLITE_VERSION, SQLITE_SOURCE_ID);
793 fossil_print("zlib %s\n", ZLIB_VERSION);
 
794 #if defined(FOSSIL_ENABLE_SSL)
795 fossil_print("SSL (%s)\n", OPENSSL_VERSION_TEXT);
 
796 #endif
797 #if defined(FOSSIL_ENABLE_TCL)
798 fossil_print("TCL (Tcl %s)\n", TCL_PATCH_LEVEL);
 
799 #endif
800 #if defined(FOSSIL_ENABLE_TCL_STUBS)
801 fossil_print("TCL_STUBS\n");
 
802 #endif
803 #if defined(FOSSIL_ENABLE_JSON)
804 fossil_print("JSON (API %s)\n", FOSSIL_JSON_API_VERSION);
 
805 #endif
 
 
 
806 }
807 }
808
809
810 /*
@@ -1811,18 +1803,19 @@
1803 zPort = find_option("port", "P", 1);
1804 zNotFound = find_option("notfound", 0, 1);
1805 zAltBase = find_option("baseurl", 0, 1);
1806 if( zAltBase ){
1807 set_base_url(zAltBase);
1808 }
1809 if ( find_option("localhost", 0, 0)!=0 ){
1810 flags |= HTTP_SERVER_LOCALHOST;
1811 }
1812 if( g.argc!=2 && g.argc!=3 ) usage("?REPOSITORY?");
1813 isUiCmd = g.argv[1][0]=='u';
1814 if( isUiCmd ){
1815 flags |= HTTP_SERVER_LOCALHOST;
1816 g.useLocalauth = 1;
 
 
1817 }
1818 find_server_repository(isUiCmd && zNotFound==0);
1819 if( zPort ){
1820 int i;
1821 for(i=strlen(zPort)-1; i>=0 && zPort[i]!=':'; i--){}
1822
--- src/makemake.tcl
+++ src/makemake.tcl
@@ -430,11 +430,11 @@
430430
# here is to use the Sysinternals junction tool to create a hard
431431
# link between a "tcl-8.x" sub-directory of the Fossil source code
432432
# directory and the target Tcl directory. This removes the need to
433433
# hard-code the necessary paths in this Makefile.
434434
#
435
-TCLDIR = $(SRCDIR)/../tcl-8.6
435
+TCLDIR = $(SRCDIR)/../compat/tcl-8.6
436436
437437
#### The Tcl source code directory. This defaults to the same value as
438438
# TCLDIR macro (above), which may not be correct. This value will
439439
# only be used if the FOSSIL_TCL_SOURCE macro is defined.
440440
#
441441
--- src/makemake.tcl
+++ src/makemake.tcl
@@ -430,11 +430,11 @@
430 # here is to use the Sysinternals junction tool to create a hard
431 # link between a "tcl-8.x" sub-directory of the Fossil source code
432 # directory and the target Tcl directory. This removes the need to
433 # hard-code the necessary paths in this Makefile.
434 #
435 TCLDIR = $(SRCDIR)/../tcl-8.6
436
437 #### The Tcl source code directory. This defaults to the same value as
438 # TCLDIR macro (above), which may not be correct. This value will
439 # only be used if the FOSSIL_TCL_SOURCE macro is defined.
440 #
441
--- src/makemake.tcl
+++ src/makemake.tcl
@@ -430,11 +430,11 @@
430 # here is to use the Sysinternals junction tool to create a hard
431 # link between a "tcl-8.x" sub-directory of the Fossil source code
432 # directory and the target Tcl directory. This removes the need to
433 # hard-code the necessary paths in this Makefile.
434 #
435 TCLDIR = $(SRCDIR)/../compat/tcl-8.6
436
437 #### The Tcl source code directory. This defaults to the same value as
438 # TCLDIR macro (above), which may not be correct. This value will
439 # only be used if the FOSSIL_TCL_SOURCE macro is defined.
440 #
441
+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
+2641 -2450
--- 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-20 14:17:39 d94db3fd921890ab1d6414ab629410ae50779686"
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";
@@ -22929,17 +22845,10 @@
2292922845
** * Definitions of sqlite3_vfs objects for all locking methods
2293022846
** plus implementations of sqlite3_os_init() and sqlite3_os_end().
2293122847
*/
2293222848
#if SQLITE_OS_UNIX /* This file is used on unix only */
2293322849
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
-
2294122850
/*
2294222851
** There are various methods for file locking used for concurrency
2294322852
** control:
2294422853
**
2294522854
** 1. POSIX locking (the default),
@@ -26866,19 +26775,23 @@
2686626775
}
2686726776
return SQLITE_OK;
2686826777
}
2686926778
case SQLITE_FCNTL_MMAP_SIZE: {
2687026779
i64 newLimit = *(i64*)pArg;
26780
+ int rc = SQLITE_OK;
2687126781
if( newLimit>sqlite3GlobalConfig.mxMmap ){
2687226782
newLimit = sqlite3GlobalConfig.mxMmap;
2687326783
}
2687426784
*(i64*)pArg = pFile->mmapSizeMax;
26875
- if( newLimit>=0 ){
26785
+ if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
2687626786
pFile->mmapSizeMax = newLimit;
26877
- if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
26787
+ if( pFile->mmapSize>0 ){
26788
+ unixUnmapfile(pFile);
26789
+ rc = unixMapfile(pFile, -1);
26790
+ }
2687826791
}
26879
- return SQLITE_OK;
26792
+ return rc;
2688026793
}
2688126794
#ifdef SQLITE_DEBUG
2688226795
/* The pager calls this method to signal that it has done
2688326796
** a rollback and that the database is therefore unchanged and
2688426797
** it hence it is OK for the transaction change counter to be
@@ -28244,11 +28157,11 @@
2824428157
OSTRACE(("OPEN %-3d %s\n", h, zFilename));
2824528158
pNew->h = h;
2824628159
pNew->pVfs = pVfs;
2824728160
pNew->zPath = zFilename;
2824828161
pNew->ctrlFlags = (u8)ctrlFlags;
28249
- pNew->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
28162
+ pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
2825028163
if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
2825128164
"psow", SQLITE_POWERSAFE_OVERWRITE) ){
2825228165
pNew->ctrlFlags |= UNIXFILE_PSOW;
2825328166
}
2825428167
if( strcmp(pVfs->zName,"unix-excl")==0 ){
@@ -30799,17 +30712,10 @@
3079930712
** This file mapping API is common to both Win32 and WinRT.
3080030713
*/
3080130714
WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
3080230715
#endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
3080330716
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
-
3081130717
/*
3081230718
** Some Microsoft compilers lack this definition.
3081330719
*/
3081430720
#ifndef INVALID_FILE_ATTRIBUTES
3081530721
# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
@@ -33531,10 +33437,13 @@
3353133437
}
3353233438
}
3353333439
3353433440
/* Forward declaration */
3353533441
static int getTempname(int nBuf, char *zBuf);
33442
+#if SQLITE_MAX_MMAP_SIZE>0
33443
+static int winMapfile(winFile*, sqlite3_int64);
33444
+#endif
3353633445
3353733446
/*
3353833447
** Control and query of the open file handle.
3353933448
*/
3354033449
static int winFileControl(sqlite3_file *id, int op, void *pArg){
@@ -33614,17 +33523,24 @@
3361433523
return SQLITE_OK;
3361533524
}
3361633525
#if SQLITE_MAX_MMAP_SIZE>0
3361733526
case SQLITE_FCNTL_MMAP_SIZE: {
3361833527
i64 newLimit = *(i64*)pArg;
33528
+ int rc = SQLITE_OK;
3361933529
if( newLimit>sqlite3GlobalConfig.mxMmap ){
3362033530
newLimit = sqlite3GlobalConfig.mxMmap;
3362133531
}
3362233532
*(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;
33533
+ if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33534
+ pFile->mmapSizeMax = newLimit;
33535
+ if( pFile->mmapSize>0 ){
33536
+ (void)winUnmapfile(pFile);
33537
+ rc = winMapfile(pFile, -1);
33538
+ }
33539
+ }
33540
+ OSTRACE(("FCNTL file=%p, rc=%d\n", pFile->h, rc));
33541
+ return rc;
3362633542
}
3362733543
#endif
3362833544
}
3362933545
OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
3363033546
return SQLITE_NOTFOUND;
@@ -33652,19 +33568,19 @@
3365233568
winFile *p = (winFile*)id;
3365333569
return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
3365433570
((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
3365533571
}
3365633572
33657
-#ifndef SQLITE_OMIT_WAL
33658
-
3365933573
/*
3366033574
** Windows will only let you create file view mappings
3366133575
** on allocation size granularity boundaries.
3366233576
** During sqlite3_os_init() we do a GetSystemInfo()
3366333577
** to get the granularity size.
3366433578
*/
3366533579
SYSTEM_INFO winSysInfo;
33580
+
33581
+#ifndef SQLITE_OMIT_WAL
3366633582
3366733583
/*
3366833584
** Helper functions to obtain and relinquish the global mutex. The
3366933585
** global mutex is used to protect the winLockInfo objects used by
3367033586
** this file, all of which may be shared by multiple threads.
@@ -34961,11 +34877,11 @@
3496134877
#if SQLITE_MAX_MMAP_SIZE>0
3496234878
pFile->hMap = NULL;
3496334879
pFile->pMapRegion = 0;
3496434880
pFile->mmapSize = 0;
3496534881
pFile->mmapSizeActual = 0;
34966
- pFile->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
34882
+ pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
3496734883
#endif
3496834884
3496934885
OpenCounter(+1);
3497034886
return rc;
3497134887
}
@@ -37220,11 +37136,11 @@
3722037136
PCache1 *pCache; /* The newly created page cache */
3722137137
PGroup *pGroup; /* The group the new page cache will belong to */
3722237138
int sz; /* Bytes of memory required to allocate the new cache */
3722337139
3722437140
/*
37225
- ** The seperateCache variable is true if each PCache has its own private
37141
+ ** The separateCache variable is true if each PCache has its own private
3722637142
** PGroup. In other words, separateCache is true for mode (1) where no
3722737143
** mutexing is required.
3722837144
**
3722937145
** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
3723037146
**
@@ -42544,11 +42460,12 @@
4254442460
/* Before the first write, give the VFS a hint of what the final
4254542461
** file size will be.
4254642462
*/
4254742463
assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
4254842464
if( rc==SQLITE_OK
42549
- && (pList->pDirty ? pPager->dbSize : pList->pgno+1)>pPager->dbHintSize
42465
+ && pPager->dbHintSize<pPager->dbSize
42466
+ && (pList->pDirty || pList->pgno>pPager->dbHintSize)
4255042467
){
4255142468
sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
4255242469
sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
4255342470
pPager->dbHintSize = pPager->dbSize;
4255442471
}
@@ -43509,11 +43426,11 @@
4350943426
** requested page is not already stored in the cache, then no
4351043427
** actual disk read occurs. In this case the memory image of the
4351143428
** page is initialized to all zeros.
4351243429
**
4351343430
** If noContent is true, it means that we do not care about the contents
43514
-** of the page. This occurs in two seperate scenarios:
43431
+** of the page. This occurs in two scenarios:
4351543432
**
4351643433
** a) When reading a free-list leaf page from the database, and
4351743434
**
4351843435
** b) When a savepoint is being rolled back and we need to load
4351943436
** a new page into the cache to be filled with the data read
@@ -44919,11 +44836,31 @@
4491944836
pagerReportSize(pPager);
4492044837
}
4492144838
SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
4492244839
return pPager->pCodec;
4492344840
}
44924
-#endif
44841
+
44842
+/*
44843
+** This function is called by the wal module when writing page content
44844
+** into the log file.
44845
+**
44846
+** This function returns a pointer to a buffer containing the encrypted
44847
+** page content. If a malloc fails, this function may return NULL.
44848
+*/
44849
+SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44850
+ void *aData = 0;
44851
+ CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44852
+ return aData;
44853
+}
44854
+
44855
+/*
44856
+** Return the current pager state
44857
+*/
44858
+SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
44859
+ return pPager->eState;
44860
+}
44861
+#endif /* SQLITE_HAS_CODEC */
4492544862
4492644863
#ifndef SQLITE_OMIT_AUTOVACUUM
4492744864
/*
4492844865
** Move the page pPg to location pgno in the file.
4492944866
**
@@ -45474,25 +45411,10 @@
4547445411
assert( pPager->eState==PAGER_READER );
4547545412
return sqlite3WalFramesize(pPager->pWal);
4547645413
}
4547745414
#endif
4547845415
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
-
4549445416
#endif /* SQLITE_OMIT_DISKIO */
4549545417
4549645418
/************** End of pager.c ***********************************************/
4549745419
/************** Begin file wal.c *********************************************/
4549845420
/*
@@ -50759,11 +50681,11 @@
5075950681
if( rc ) return rc;
5076050682
top = get2byteNotZero(&data[hdr+5]);
5076150683
}else if( gap+2<=top ){
5076250684
/* Search the freelist looking for a free slot big enough to satisfy
5076350685
** the request. The allocation is made from the first free slot in
50764
- ** the list that is large enough to accomadate it.
50686
+ ** the list that is large enough to accommodate it.
5076550687
*/
5076650688
int pc, addr;
5076750689
for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
5076850690
int size; /* Size of the free slot */
5076950691
if( pc>usableSize-4 || pc<addr+4 ){
@@ -52702,11 +52624,11 @@
5270252624
return rc;
5270352625
}
5270452626
5270552627
/*
5270652628
** This routine is called prior to sqlite3PagerCommit when a transaction
52707
-** is commited for an auto-vacuum database.
52629
+** is committed for an auto-vacuum database.
5270852630
**
5270952631
** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
5271052632
** the database file should be truncated to during the commit process.
5271152633
** i.e. the database has been reorganized so that only the first *pnTrunc
5271252634
** pages are in use.
@@ -58045,16 +57967,10 @@
5804557967
*************************************************************************
5804657968
** This file contains the implementation of the sqlite3_backup_XXX()
5804757969
** API functions and the related features.
5804857970
*/
5804957971
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
-
5805657972
/*
5805757973
** Structure allocated for each backup operation.
5805857974
*/
5805957975
struct sqlite3_backup {
5806057976
sqlite3* pDestDb; /* Destination database handle */
@@ -61942,11 +61858,11 @@
6194261858
/*
6194361859
** If the Vdbe passed as the first argument opened a statement-transaction,
6194461860
** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
6194561861
** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
6194661862
** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61947
-** statement transaction is commtted.
61863
+** statement transaction is committed.
6194861864
**
6194961865
** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
6195061866
** Otherwise SQLITE_OK.
6195161867
*/
6195261868
SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
@@ -64011,17 +63927,10 @@
6401163927
int iType = sqlite3_value_type( columnMem(pStmt,i) );
6401263928
columnMallocFailure(pStmt);
6401363929
return iType;
6401463930
}
6401563931
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
-
6402363932
/*
6402463933
** Convert the N-th element of pStmt->pColName[] into a string using
6402563934
** xFunc() then return that string. If N is out of range, return 0.
6402663935
**
6402763936
** There are up to 5 names for each column. useType determines which
@@ -64643,18 +64552,18 @@
6464364552
pVar = &utf8;
6464464553
}
6464564554
#endif
6464664555
nOut = pVar->n;
6464764556
#ifdef SQLITE_TRACE_SIZE_LIMIT
64648
- if( n>SQLITE_TRACE_SIZE_LIMIT ){
64557
+ if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
6464964558
nOut = SQLITE_TRACE_SIZE_LIMIT;
64650
- while( nOut<pVar->n && (pVar->z[n]&0xc0)==0x80 ){ n++; }
64559
+ while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
6465164560
}
6465264561
#endif
6465364562
sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
6465464563
#ifdef SQLITE_TRACE_SIZE_LIMIT
64655
- if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-n);
64564
+ if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
6465664565
#endif
6465764566
#ifndef SQLITE_OMIT_UTF16
6465864567
if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
6465964568
#endif
6466064569
}else if( pVar->flags & MEM_Zero ){
@@ -64670,11 +64579,11 @@
6467064579
for(i=0; i<nOut; i++){
6467164580
sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
6467264581
}
6467364582
sqlite3StrAccumAppend(&out, "'", 1);
6467464583
#ifdef SQLITE_TRACE_SIZE_LIMIT
64675
- if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-n);
64584
+ if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
6467664585
#endif
6467764586
}
6467864587
}
6467964588
}
6468064589
return sqlite3StrAccumFinish(&out);
@@ -68269,12 +68178,12 @@
6826968178
** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
6827068179
** obtained on the database file when a write-transaction is started. No
6827168180
** other process can start another write transaction while this transaction is
6827268181
** underway. Starting a write transaction also creates a rollback journal. A
6827368182
** 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.
68183
+** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
68184
+** also obtained on the file.
6827668185
**
6827768186
** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
6827868187
** true (this flag is set if the Vdbe may modify more than one row and may
6827968188
** throw an ABORT exception), a statement transaction may also be opened.
6828068189
** More specifically, a statement transaction is opened iff the database
@@ -72224,11 +72133,11 @@
7222472133
**
7222572134
** For the purposes of this comparison, EOF is considered greater than any
7222672135
** other key value. If the keys are equal (only possible with two EOF
7222772136
** values), it doesn't matter which index is stored.
7222872137
**
72229
-** The (N/4) elements of aTree[] that preceed the final (N/2) described
72138
+** The (N/4) elements of aTree[] that precede the final (N/2) described
7223072139
** above contains the index of the smallest of each block of 4 iterators.
7223172140
** And so on. So that aTree[1] contains the index of the iterator that
7223272141
** currently points to the smallest key value. aTree[0] is unused.
7223372142
**
7223472143
** Example:
@@ -73499,16 +73408,10 @@
7349973408
** a power-of-two allocation. This mimimizes wasted space in power-of-two
7350073409
** memory allocators.
7350173410
*/
7350273411
#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
7350373412
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
-
7351073413
/*
7351173414
** The rollback journal is composed of a linked list of these structures.
7351273415
*/
7351373416
struct FileChunk {
7351473417
FileChunk *pNext; /* Next chunk in the journal */
@@ -75045,12 +74948,12 @@
7504574948
**
7504674949
** Minor point: If this is the case, then the expression will be
7504774950
** re-evaluated for each reference to it.
7504874951
*/
7504974952
sNC.pEList = p->pEList;
75050
- if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
7505174953
sNC.ncFlags |= NC_AsMaybe;
74954
+ if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
7505274955
if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
7505374956
sNC.ncFlags &= ~NC_AsMaybe;
7505474957
7505574958
/* The ORDER BY and GROUP BY clauses may not refer to terms in
7505674959
** outer queries
@@ -76817,19 +76720,19 @@
7681776720
7681876721
if( eType==0 ){
7681976722
/* Could not found an existing table or index to use as the RHS b-tree.
7682076723
** We will have to generate an ephemeral table to do the job.
7682176724
*/
76822
- double savedNQueryLoop = pParse->nQueryLoop;
76725
+ u32 savedNQueryLoop = pParse->nQueryLoop;
7682376726
int rMayHaveNull = 0;
7682476727
eType = IN_INDEX_EPH;
7682576728
if( prNotFound ){
7682676729
*prNotFound = rMayHaveNull = ++pParse->nMem;
7682776730
sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
7682876731
}else{
76829
- testcase( pParse->nQueryLoop>(double)1 );
76830
- pParse->nQueryLoop = (double)1;
76732
+ testcase( pParse->nQueryLoop>0 );
76733
+ pParse->nQueryLoop = 0;
7683176734
if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
7683276735
eType = IN_INDEX_ROWID;
7683376736
}
7683476737
}
7683576738
sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
@@ -76867,11 +76770,11 @@
7686776770
** the register given by rMayHaveNull to NULL. Calling routines will take
7686876771
** care of changing this register value to non-NULL if the RHS is NULL-free.
7686976772
**
7687076773
** If rMayHaveNull is zero, that means that the subquery is being used
7687176774
** for membership testing only. There is no need to initialize any
76872
-** registers to indicate the presense or absence of NULLs on the RHS.
76775
+** registers to indicate the presence or absence of NULLs on the RHS.
7687376776
**
7687476777
** For a SELECT or EXISTS operator, return the register that holds the
7687576778
** result. For IN operators or if an error occurs, the return value is 0.
7687676779
*/
7687776780
#ifndef SQLITE_OMIT_SUBQUERY
@@ -80267,11 +80170,11 @@
8026780170
**
8026880171
** Additional tables might be added in future releases of SQLite.
8026980172
** The sqlite_stat2 table is not created or used unless the SQLite version
8027080173
** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
8027180174
** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
80272
-** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80175
+** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
8027380176
** created and used by SQLite versions 3.7.9 and later and with
8027480177
** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
8027580178
** is a superset of sqlite_stat2.
8027680179
**
8027780180
** Format of sqlite_stat1:
@@ -83455,10 +83358,11 @@
8345583358
zColl = sqlite3NameFromToken(db, pToken);
8345683359
if( !zColl ) return;
8345783360
8345883361
if( sqlite3LocateCollSeq(pParse, zColl) ){
8345983362
Index *pIdx;
83363
+ sqlite3DbFree(db, p->aCol[i].zColl);
8346083364
p->aCol[i].zColl = zColl;
8346183365
8346283366
/* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
8346383367
** then an index may have been created on this column before the
8346483368
** collation type was added. Correct this if it is the case.
@@ -84874,10 +84778,11 @@
8487484778
zExtra = (char *)(&pIndex->zName[nName+1]);
8487584779
memcpy(pIndex->zName, zName, nName+1);
8487684780
pIndex->pTable = pTab;
8487784781
pIndex->nColumn = pList->nExpr;
8487884782
pIndex->onError = (u8)onError;
84783
+ pIndex->uniqNotNull = onError==OE_Abort;
8487984784
pIndex->autoIndex = (u8)(pName==0);
8488084785
pIndex->pSchema = db->aDb[iDb].pSchema;
8488184786
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
8488284787
8488384788
/* Check to see if we should honor DESC requests on index columns
@@ -84932,10 +84837,11 @@
8493284837
goto exit_create_index;
8493384838
}
8493484839
pIndex->azColl[i] = zColl;
8493584840
requestedSortOrder = pListItem->sortOrder & sortOrderMask;
8493684841
pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84842
+ if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
8493784843
}
8493884844
sqlite3DefaultRowEst(pIndex);
8493984845
8494084846
if( pTab==pParse->pNewTable ){
8494184847
/* This routine has been called to create an automatic index as a
@@ -85363,19 +85269,19 @@
8536385269
assert( db->mallocFailed );
8536485270
return pSrc;
8536585271
}
8536685272
pSrc = pNew;
8536785273
nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85368
- pSrc->nAlloc = (u16)nGot;
85274
+ pSrc->nAlloc = (u8)nGot;
8536985275
}
8537085276
8537185277
/* Move existing slots that come after the newly inserted slots
8537285278
** out of the way */
8537385279
for(i=pSrc->nSrc-1; i>=iStart; i--){
8537485280
pSrc->a[i+nExtra] = pSrc->a[i];
8537585281
}
85376
- pSrc->nSrc += (i16)nExtra;
85282
+ pSrc->nSrc += (i8)nExtra;
8537785283
8537885284
/* Zero the newly allocated slots */
8537985285
memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
8538085286
for(i=iStart; i<iStart+nExtra; i++){
8538185287
pSrc->a[i].iCursor = -1;
@@ -87378,11 +87284,11 @@
8737887284
** of x. If x is text, then we actually count UTF-8 characters.
8737987285
** If x is a blob, then we count bytes.
8738087286
**
8738187287
** If p1 is negative, then we begin abs(p1) from the end of x[].
8738287288
**
87383
-** If p2 is negative, return the p2 characters preceeding p1.
87289
+** If p2 is negative, return the p2 characters preceding p1.
8738487290
*/
8738587291
static void substrFunc(
8738687292
sqlite3_context *context,
8738787293
int argc,
8738887294
sqlite3_value **argv
@@ -88037,14 +87943,10 @@
8803787943
'0', '1', '2', '3', '4', '5', '6', '7',
8803887944
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
8803987945
};
8804087946
8804187947
/*
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
-**
8804687948
** Implementation of the QUOTE() function. This function takes a single
8804787949
** argument. If the argument is numeric, the return value is the same as
8804887950
** the argument. If the argument is NULL, the return value is the string
8804987951
** "NULL". Otherwise, the argument is enclosed in single quotes with
8805087952
** single-quote escapes.
@@ -88229,11 +88131,11 @@
8822988131
}
8823088132
8823188133
/*
8823288134
** The replace() function. Three arguments are all strings: call
8823388135
** 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
88136
+** from A by replacing every occurrence of B with C. The match
8823588137
** must be exact. Collating sequences are not used.
8823688138
*/
8823788139
static void replaceFunc(
8823888140
sqlite3_context *context,
8823988141
int argc,
@@ -94147,15 +94049,19 @@
9414794049
sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
9414894050
}
9414994051
}
9415094052
}
9415194053
sz = -1;
94152
- if( sqlite3_file_control(db,zDb,SQLITE_FCNTL_MMAP_SIZE,&sz)==SQLITE_OK ){
94054
+ rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
9415394055
#if SQLITE_MAX_MMAP_SIZE==0
94154
- sz = 0;
94056
+ sz = 0;
9415594057
#endif
94058
+ if( rc==SQLITE_OK ){
9415694059
returnSingleInt(pParse, "mmap_size", sz);
94060
+ }else if( rc!=SQLITE_NOTFOUND ){
94061
+ pParse->nErr++;
94062
+ pParse->rc = rc;
9415794063
}
9415894064
}else
9415994065
9416094066
/*
9416194067
** PRAGMA temp_store
@@ -94682,11 +94588,11 @@
9468294588
#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
9468394589
# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
9468494590
#endif
9468594591
9468694592
#ifndef SQLITE_OMIT_INTEGRITY_CHECK
94687
- /* Pragma "quick_check" is an experimental reduced version of
94593
+ /* Pragma "quick_check" is reduced version of
9468894594
** integrity_check designed to detect most database corruption
9468994595
** without most of the overhead of a full integrity-check.
9469094596
*/
9469194597
if( sqlite3StrICmp(zLeft, "integrity_check")==0
9469294598
|| sqlite3StrICmp(zLeft, "quick_check")==0
@@ -95140,14 +95046,14 @@
9514095046
}else
9514195047
#endif
9514295048
9514395049
#ifdef SQLITE_HAS_CODEC
9514495050
if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95145
- sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
95051
+ sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
9514695052
}else
9514795053
if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95148
- sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
95054
+ sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
9514995055
}else
9515095056
if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
9515195057
sqlite3StrICmp(zLeft, "hexrekey")==0) ){
9515295058
int i, h1, h2;
9515395059
char zKey[40];
@@ -95155,13 +95061,13 @@
9515595061
h1 += 9*(1&(h1>>6));
9515695062
h2 += 9*(1&(h2>>6));
9515795063
zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
9515895064
}
9515995065
if( (zLeft[3] & 0xf)==0xb ){
95160
- sqlite3_key(db, zKey, i/2);
95066
+ sqlite3_key_v2(db, zDb, zKey, i/2);
9516195067
}else{
95162
- sqlite3_rekey(db, zKey, i/2);
95068
+ sqlite3_rekey_v2(db, zDb, zKey, i/2);
9516395069
}
9516495070
}else
9516595071
#endif
9516695072
#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
9516795073
if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
@@ -95792,11 +95698,11 @@
9579295698
}
9579395699
9579495700
sqlite3VtabUnlockList(db);
9579595701
9579695702
pParse->db = db;
95797
- pParse->nQueryLoop = (double)1;
95703
+ pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
9579895704
if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
9579995705
char *zSqlCopy;
9580095706
int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
9580195707
testcase( nBytes==mxLen );
9580295708
testcase( nBytes==mxLen+1 );
@@ -95814,11 +95720,11 @@
9581495720
pParse->zTail = &zSql[nBytes];
9581595721
}
9581695722
}else{
9581795723
sqlite3RunParser(pParse, zSql, &zErrMsg);
9581895724
}
95819
- assert( 1==(int)pParse->nQueryLoop );
95725
+ assert( 0==pParse->nQueryLoop );
9582095726
9582195727
if( db->mallocFailed ){
9582295728
pParse->rc = SQLITE_NOMEM;
9582395729
}
9582495730
if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
@@ -96178,11 +96084,11 @@
9617896084
sqlite3DbFree(db, p);
9617996085
}
9618096086
}
9618196087
9618296088
/*
96183
-** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
96089
+** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
9618496090
** type of join. Return an integer constant that expresses that type
9618596091
** in terms of the following bit values:
9618696092
**
9618796093
** JT_INNER
9618896094
** JT_CROSS
@@ -97592,11 +97498,11 @@
9759297498
int addr1, n;
9759397499
if( p->iLimit ) return;
9759497500
9759597501
/*
9759697502
** "LIMIT -1" always shows all rows. There is some
97597
- ** contraversy about what the correct behavior should be.
97503
+ ** controversy about what the correct behavior should be.
9759897504
** The current implementation interprets "LIMIT 0" to mean
9759997505
** no rows.
9760097506
*/
9760197507
sqlite3ExprCacheClear(pParse);
9760297508
assert( p->pOffset==0 || p->pLimit!=0 );
@@ -97607,12 +97513,12 @@
9760797513
if( sqlite3ExprIsInteger(p->pLimit, &n) ){
9760897514
sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
9760997515
VdbeComment((v, "LIMIT counter"));
9761097516
if( n==0 ){
9761197517
sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97612
- }else{
97613
- if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97518
+ }else if( n>=0 && p->nSelectRow>(u64)n ){
97519
+ p->nSelectRow = n;
9761497520
}
9761597521
}else{
9761697522
sqlite3ExprCode(pParse, p->pLimit, iLimit);
9761797523
sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
9761897524
VdbeComment((v, "LIMIT counter"));
@@ -97802,13 +97708,13 @@
9780297708
pDelete = p->pPrior;
9780397709
p->pPrior = pPrior;
9780497710
p->nSelectRow += pPrior->nSelectRow;
9780597711
if( pPrior->pLimit
9780697712
&& sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97807
- && p->nSelectRow > (double)nLimit
97713
+ && nLimit>0 && p->nSelectRow > (u64)nLimit
9780897714
){
97809
- p->nSelectRow = (double)nLimit;
97715
+ p->nSelectRow = nLimit;
9781097716
}
9781197717
if( addr ){
9781297718
sqlite3VdbeJumpHere(v, addr);
9781397719
}
9781497720
break;
@@ -99953,15 +99859,14 @@
9995399859
Parse *pParse, /* Parse context */
9995499860
Table *pTab, /* Table being queried */
9995599861
Index *pIdx /* Index used to optimize scan, or NULL */
9995699862
){
9995799863
if( pParse->explain==2 ){
99958
- char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99864
+ char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
9995999865
pTab->zName,
99960
- pIdx ? "USING COVERING INDEX " : "",
99961
- pIdx ? pIdx->zName : "",
99962
- pTab->nRowEst
99866
+ pIdx ? " USING COVERING INDEX " : "",
99867
+ pIdx ? pIdx->zName : ""
9996399868
);
9996499869
sqlite3VdbeAddOp4(
9996599870
pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
9996699871
);
9996799872
}
@@ -100115,11 +100020,11 @@
100115100020
}
100116100021
continue;
100117100022
}
100118100023
100119100024
/* Increment Parse.nHeight by the height of the largest expression
100120
- ** tree refered to by this, the parent select. The child select
100025
+ ** tree referred to by this, the parent select. The child select
100121100026
** may contain expression trees of at most
100122100027
** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100123100028
** more conservative than necessary, but much easier than enforcing
100124100029
** an exact limit.
100125100030
*/
@@ -100308,11 +100213,11 @@
100308100213
}
100309100214
100310100215
/* Set the limiter.
100311100216
*/
100312100217
iEnd = sqlite3VdbeMakeLabel(v);
100313
- p->nSelectRow = (double)LARGEST_INT64;
100218
+ p->nSelectRow = LARGEST_INT64;
100314100219
computeLimitRegisters(pParse, p, iEnd);
100315100220
if( p->iLimit==0 && addrSortIndex>=0 ){
100316100221
sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100317100222
p->selFlags |= SF_UseSorter;
100318100223
}
@@ -100336,13 +100241,17 @@
100336100241
ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100337100242
100338100243
/* Begin the database scan. */
100339100244
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100340100245
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;
100246
+ if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
100247
+ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
100248
+ }
100249
+ if( sqlite3WhereIsDistinct(pWInfo) ){
100250
+ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
100251
+ }
100252
+ if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
100344100253
100345100254
/* If sorting index that was created by a prior OP_OpenEphemeral
100346100255
** instruction ended up not being needed, then change the OP_OpenEphemeral
100347100256
** into an OP_Noop.
100348100257
*/
@@ -100351,11 +100260,12 @@
100351100260
p->addrOpenEphm[2] = -1;
100352100261
}
100353100262
100354100263
/* Use the standard inner loop. */
100355100264
selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100356
- pWInfo->iContinue, pWInfo->iBreak);
100265
+ sqlite3WhereContinueLabel(pWInfo),
100266
+ sqlite3WhereBreakLabel(pWInfo));
100357100267
100358100268
/* End the database scan loop.
100359100269
*/
100360100270
sqlite3WhereEnd(pWInfo);
100361100271
}else{
@@ -100384,13 +100294,13 @@
100384100294
pItem->iAlias = 0;
100385100295
}
100386100296
for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100387100297
pItem->iAlias = 0;
100388100298
}
100389
- if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
100299
+ if( p->nSelectRow>100 ) p->nSelectRow = 100;
100390100300
}else{
100391
- p->nSelectRow = (double)1;
100301
+ p->nSelectRow = 1;
100392100302
}
100393100303
100394100304
100395100305
/* Create a label to jump to when we want to abort the query */
100396100306
addrEnd = sqlite3VdbeMakeLabel(v);
@@ -100466,13 +100376,14 @@
100466100376
** This might involve two separate loops with an OP_Sort in between, or
100467100377
** it might be a single loop that uses an index to extract information
100468100378
** in the right order to begin with.
100469100379
*/
100470100380
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100471
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
100381
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
100382
+ WHERE_GROUPBY, 0);
100472100383
if( pWInfo==0 ) goto select_end;
100473
- if( pWInfo->nOBSat==pGroupBy->nExpr ){
100384
+ if( sqlite3WhereIsOrdered(pWInfo) ){
100474100385
/* The optimizer is able to deliver rows in group by order so
100475100386
** we do not have to sort. The OP_OpenEphemeral table will be
100476100387
** cancelled later because we still need to use the pKeyInfo
100477100388
*/
100478100389
groupBySort = 0;
@@ -100749,12 +100660,12 @@
100749100660
sqlite3ExprListDelete(db, pDel);
100750100661
goto select_end;
100751100662
}
100752100663
updateAccumulator(pParse, &sAggInfo);
100753100664
assert( pMinMax==0 || pMinMax->nExpr==1 );
100754
- if( pWInfo->nOBSat>0 ){
100755
- sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100665
+ if( sqlite3WhereIsOrdered(pWInfo) ){
100666
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
100756100667
VdbeComment((v, "%s() by index",
100757100668
(flag==WHERE_ORDERBY_MIN?"min":"max")));
100758100669
}
100759100670
sqlite3WhereEnd(pWInfo);
100760100671
finalizeAggFunctions(pParse, &sAggInfo);
@@ -102109,11 +102020,11 @@
102109102020
}
102110102021
102111102022
/*
102112102023
** This is called to code the required FOR EACH ROW triggers for an operation
102113102024
** 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
102025
+** is given by the op parameter. The tr_tm parameter determines whether the
102115102026
** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102116102027
** parameter pChanges is passed the list of columns being modified.
102117102028
**
102118102029
** If there are no triggers that fire at the specified time for the specified
102119102030
** operation on pTab, this function is a no-op.
@@ -102560,11 +102471,11 @@
102560102471
sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102561102472
pWInfo = sqlite3WhereBegin(
102562102473
pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102563102474
);
102564102475
if( pWInfo==0 ) goto update_cleanup;
102565
- okOnePass = pWInfo->okOnePass;
102476
+ okOnePass = sqlite3WhereOkOnePass(pWInfo);
102566102477
102567102478
/* Remember the rowid of every item to be updated.
102568102479
*/
102569102480
sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102570102481
if( !okOnePass ){
@@ -104397,22 +104308,165 @@
104397104308
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104398104309
/***/ int sqlite3WhereTrace = 0;
104399104310
#endif
104400104311
#if defined(SQLITE_DEBUG) \
104401104312
&& (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104402
-# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
104313
+# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
104314
+# define WHERETRACE_ENABLED 1
104403104315
#else
104404
-# define WHERETRACE(X)
104316
+# define WHERETRACE(K,X)
104405104317
#endif
104406104318
104407104319
/* Forward reference
104408104320
*/
104409104321
typedef struct WhereClause WhereClause;
104410104322
typedef struct WhereMaskSet WhereMaskSet;
104411104323
typedef struct WhereOrInfo WhereOrInfo;
104412104324
typedef struct WhereAndInfo WhereAndInfo;
104413
-typedef struct WhereCost WhereCost;
104325
+typedef struct WhereLevel WhereLevel;
104326
+typedef struct WhereLoop WhereLoop;
104327
+typedef struct WherePath WherePath;
104328
+typedef struct WhereTerm WhereTerm;
104329
+typedef struct WhereLoopBuilder WhereLoopBuilder;
104330
+typedef struct WhereScan WhereScan;
104331
+
104332
+/*
104333
+** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
104334
+** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
104335
+** (Virtual tables can return a larger cost, but let's assume they do not.)
104336
+** So all costs can be stored in a 16-bit unsigned integer without risk
104337
+** of overflow.
104338
+**
104339
+** Costs are estimates, so don't go to the computational trouble to compute
104340
+** 10*log2(X) exactly. Instead, a close estimate is used. Any value of
104341
+** X<=1 is stored as 0. X=2 is 10. X=3 is 16. X=1000 is 99. etc.
104342
+**
104343
+** The tool/wherecosttest.c source file implements a command-line program
104344
+** that will convert between WhereCost to integers and do addition and
104345
+** multiplication on WhereCost values. That command-line program is a
104346
+** useful utility to have around when working with this module.
104347
+*/
104348
+typedef unsigned short int WhereCost;
104349
+
104350
+/*
104351
+** This object contains information needed to implement a single nested
104352
+** loop in WHERE clause.
104353
+**
104354
+** Contrast this object with WhereLoop. This object describes the
104355
+** implementation of the loop. WhereLoop describes the algorithm.
104356
+** This object contains a pointer to the WhereLoop algorithm as one of
104357
+** its elements.
104358
+**
104359
+** The WhereInfo object contains a single instance of this object for
104360
+** each term in the FROM clause (which is to say, for each of the
104361
+** nested loops as implemented). The order of WhereLevel objects determines
104362
+** the loop nested order, with WhereInfo.a[0] being the outer loop and
104363
+** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
104364
+*/
104365
+struct WhereLevel {
104366
+ int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
104367
+ int iTabCur; /* The VDBE cursor used to access the table */
104368
+ int iIdxCur; /* The VDBE cursor used to access pIdx */
104369
+ int addrBrk; /* Jump here to break out of the loop */
104370
+ int addrNxt; /* Jump here to start the next IN combination */
104371
+ int addrCont; /* Jump here to continue with the next loop cycle */
104372
+ int addrFirst; /* First instruction of interior of the loop */
104373
+ u8 iFrom; /* Which entry in the FROM clause */
104374
+ u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
104375
+ int p1, p2; /* Operands of the opcode used to ends the loop */
104376
+ union { /* Information that depends on pWLoop->wsFlags */
104377
+ struct {
104378
+ int nIn; /* Number of entries in aInLoop[] */
104379
+ struct InLoop {
104380
+ int iCur; /* The VDBE cursor used by this IN operator */
104381
+ int addrInTop; /* Top of the IN loop */
104382
+ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
104383
+ } *aInLoop; /* Information about each nested IN operator */
104384
+ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
104385
+ Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
104386
+ } u;
104387
+ struct WhereLoop *pWLoop; /* The selected WhereLoop object */
104388
+};
104389
+
104390
+/*
104391
+** Each instance of this object represents an algorithm for evaluating one
104392
+** term of a join. Every term of the FROM clause will have at least
104393
+** one corresponding WhereLoop object (unless INDEXED BY constraints
104394
+** prevent a query solution - which is an error) and many terms of the
104395
+** FROM clause will have multiple WhereLoop objects, each describing a
104396
+** potential way of implementing that FROM-clause term, together with
104397
+** dependencies and cost estimates for using the chosen algorithm.
104398
+**
104399
+** Query planning consists of building up a collection of these WhereLoop
104400
+** objects, then computing a particular sequence of WhereLoop objects, with
104401
+** one WhereLoop object per FROM clause term, that satisfy all dependencies
104402
+** and that minimize the overall cost.
104403
+*/
104404
+struct WhereLoop {
104405
+ Bitmask prereq; /* Bitmask of other loops that must run first */
104406
+ Bitmask maskSelf; /* Bitmask identifying table iTab */
104407
+#ifdef SQLITE_DEBUG
104408
+ char cId; /* Symbolic ID of this loop for debugging use */
104409
+#endif
104410
+ u8 iTab; /* Position in FROM clause of table for this loop */
104411
+ u8 iSortIdx; /* Sorting index number. 0==None */
104412
+ WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
104413
+ WhereCost rRun; /* Cost of running each loop */
104414
+ WhereCost nOut; /* Estimated number of output rows */
104415
+ union {
104416
+ struct { /* Information for internal btree tables */
104417
+ int nEq; /* Number of equality constraints */
104418
+ Index *pIndex; /* Index used, or NULL */
104419
+ } btree;
104420
+ struct { /* Information for virtual tables */
104421
+ int idxNum; /* Index number */
104422
+ u8 needFree; /* True if sqlite3_free(idxStr) is needed */
104423
+ u8 isOrdered; /* True if satisfies ORDER BY */
104424
+ u16 omitMask; /* Terms that may be omitted */
104425
+ char *idxStr; /* Index identifier string */
104426
+ } vtab;
104427
+ } u;
104428
+ u32 wsFlags; /* WHERE_* flags describing the plan */
104429
+ u16 nLTerm; /* Number of entries in aLTerm[] */
104430
+ /**** whereLoopXfer() copies fields above ***********************/
104431
+# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
104432
+ u16 nLSlot; /* Number of slots allocated for aLTerm[] */
104433
+ WhereTerm **aLTerm; /* WhereTerms used */
104434
+ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
104435
+ WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
104436
+};
104437
+
104438
+/* Forward declaration of methods */
104439
+static int whereLoopResize(sqlite3*, WhereLoop*, int);
104440
+
104441
+/*
104442
+** Each instance of this object holds a sequence of WhereLoop objects
104443
+** that implement some or all of a query plan.
104444
+**
104445
+** Think of each WhereLoop objects as a node in a graph, which arcs
104446
+** showing dependences and costs for travelling between nodes. (That is
104447
+** not a completely accurate description because WhereLoop costs are a
104448
+** vector, not a scalar, and because dependences are many-to-one, not
104449
+** one-to-one as are graph nodes. But it is a useful visualization aid.)
104450
+** Then a WherePath object is a path through the graph that visits some
104451
+** or all of the WhereLoop objects once.
104452
+**
104453
+** The "solver" works by creating the N best WherePath objects of length
104454
+** 1. Then using those as a basis to compute the N best WherePath objects
104455
+** of length 2. And so forth until the length of WherePaths equals the
104456
+** number of nodes in the FROM clause. The best (lowest cost) WherePath
104457
+** at the end is the choosen query plan.
104458
+*/
104459
+struct WherePath {
104460
+ Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
104461
+ Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
104462
+ WhereCost nRow; /* Estimated number of rows generated by this path */
104463
+ WhereCost rCost; /* Total cost of this path */
104464
+ u8 isOrdered; /* True if this path satisfies ORDER BY */
104465
+ u8 isOrderedValid; /* True if the isOrdered field is valid */
104466
+ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
104467
+};
104414104468
104415104469
/*
104416104470
** The query generator uses an array of instances of this structure to
104417104471
** help it analyze the subexpressions of the WHERE clause. Each WHERE
104418104472
** clause subexpression is separated from the others by AND operators,
@@ -104461,11 +104515,10 @@
104461104515
**
104462104516
** The number of terms in a join is limited by the number of bits
104463104517
** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
104464104518
** is only able to process joins with 64 or fewer tables.
104465104519
*/
104466
-typedef struct WhereTerm WhereTerm;
104467104520
struct WhereTerm {
104468104521
Expr *pExpr; /* Pointer to the subexpression that is this term */
104469104522
int iParent; /* Disable pWC->a[iParent] when this term disabled */
104470104523
int leftCursor; /* Cursor number of X in "X <op> <expr>" */
104471104524
union {
@@ -104495,10 +104548,26 @@
104495104548
# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
104496104549
#else
104497104550
# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
104498104551
#endif
104499104552
104553
+/*
104554
+** An instance of the WhereScan object is used as an iterator for locating
104555
+** terms in the WHERE clause that are useful to the query planner.
104556
+*/
104557
+struct WhereScan {
104558
+ WhereClause *pOrigWC; /* Original, innermost WhereClause */
104559
+ WhereClause *pWC; /* WhereClause currently being scanned */
104560
+ char *zCollName; /* Required collating sequence, if not NULL */
104561
+ char idxaff; /* Must match this affinity, if zCollName!=NULL */
104562
+ unsigned char nEquiv; /* Number of entries in aEquiv[] */
104563
+ unsigned char iEquiv; /* Next unused slot in aEquiv[] */
104564
+ u32 opMask; /* Acceptable operators */
104565
+ int k; /* Resume scanning at this->pWC->a[this->k] */
104566
+ int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
104567
+};
104568
+
104500104569
/*
104501104570
** An instance of the following structure holds all information about a
104502104571
** WHERE clause. Mostly this is a container for one or more WhereTerms.
104503104572
**
104504104573
** Explanation of pOuter: For a WHERE clause of the form
@@ -104508,15 +104577,13 @@
104508104577
** There are separate WhereClause objects for the whole clause and for
104509104578
** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
104510104579
** subclauses points to the WhereClause object for the whole clause.
104511104580
*/
104512104581
struct WhereClause {
104513
- Parse *pParse; /* The parser context */
104514
- WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
104582
+ WhereInfo *pWInfo; /* WHERE clause processing context */
104515104583
WhereClause *pOuter; /* Outer conjunction */
104516104584
u8 op; /* Split operator. TK_AND or TK_OR */
104517
- u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
104518104585
int nTerm; /* Number of terms */
104519104586
int nSlot; /* Number of entries in a[] */
104520104587
WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
104521104588
#if defined(SQLITE_SMALL_STACK)
104522104589
WhereTerm aStatic[1]; /* Initial static space for a[] */
@@ -104572,23 +104639,59 @@
104572104639
int n; /* Number of assigned cursor values */
104573104640
int ix[BMS]; /* Cursor assigned to each bit */
104574104641
};
104575104642
104576104643
/*
104577
-** A WhereCost object records a lookup strategy and the estimated
104578
-** cost of pursuing that strategy.
104644
+** This object is a convenience wrapper holding all information needed
104645
+** to construct WhereLoop objects for a particular query.
104579104646
*/
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 */
104647
+struct WhereLoopBuilder {
104648
+ WhereInfo *pWInfo; /* Information about this WHERE */
104649
+ WhereClause *pWC; /* WHERE clause terms */
104650
+ ExprList *pOrderBy; /* ORDER BY clause */
104651
+ WhereLoop *pNew; /* Template WhereLoop */
104652
+ WhereLoop *pBest; /* If non-NULL, store single best loop here */
104584104653
};
104585104654
104586104655
/*
104587
-** Bitmasks for the operators that indices are able to exploit. An
104656
+** The WHERE clause processing routine has two halves. The
104657
+** first part does the start of the WHERE loop and the second
104658
+** half does the tail of the WHERE loop. An instance of
104659
+** this structure is returned by the first half and passed
104660
+** into the second half to give some continuity.
104661
+**
104662
+** An instance of this object holds the complete state of the query
104663
+** planner.
104664
+*/
104665
+struct WhereInfo {
104666
+ Parse *pParse; /* Parsing and code generating context */
104667
+ SrcList *pTabList; /* List of tables in the join */
104668
+ ExprList *pOrderBy; /* The ORDER BY clause or NULL */
104669
+ ExprList *pDistinct; /* DISTINCT ON values, or NULL */
104670
+ WhereLoop *pLoops; /* List of all WhereLoop objects */
104671
+ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
104672
+ WhereCost nRowOut; /* Estimated number of output rows */
104673
+ u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
104674
+ u8 bOBSat; /* ORDER BY satisfied by indices */
104675
+ u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
104676
+ u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
104677
+ u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
104678
+ int iTop; /* The very beginning of the WHERE loop */
104679
+ int iContinue; /* Jump here to continue with next record */
104680
+ int iBreak; /* Jump here to break out of the loop */
104681
+ int nLevel; /* Number of nested loop */
104682
+ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
104683
+ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
104684
+ WhereClause sWC; /* Decomposition of the WHERE clause */
104685
+ WhereLevel a[1]; /* Information about each nest loop in WHERE */
104686
+};
104687
+
104688
+/*
104689
+** Bitmasks for the operators on WhereTerm objects. These are all
104690
+** operators that are of interest to the query planner. An
104588104691
** OR-ed combination of these values can be used when searching for
104589
-** terms in the where clause.
104692
+** particular WhereTerms within a WhereClause.
104590104693
*/
104591104694
#define WO_IN 0x001
104592104695
#define WO_EQ 0x002
104593104696
#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
104594104697
#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -104603,96 +104706,106 @@
104603104706
104604104707
#define WO_ALL 0xfff /* Mask of all possible WO_* values */
104605104708
#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
104606104709
104607104710
/*
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;
104711
+** These are definitions of bits in the WhereLoop.wsFlags field.
104712
+** The particular combination of bits in each WhereLoop help to
104713
+** determine the algorithm that WhereLoop represents.
104714
+*/
104715
+#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR or x IN (...) or x IS NULL */
104716
+#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
104717
+#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
104718
+#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
104719
+#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
104720
+#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
104721
+#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
104722
+#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
104723
+#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
104724
+#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
104725
+#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
104726
+#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
104727
+#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
104728
+#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
104729
+#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
104730
+#define WHERE_TEMP_INDEX 0x00004000 /* Uses an ephemeral index */
104731
+
104732
+
104733
+/* Convert a WhereCost value (10 times log2(X)) into its integer value X.
104734
+** A rough approximation is used. The value returned is not exact.
104735
+*/
104736
+static u64 whereCostToInt(WhereCost x){
104737
+ u64 n;
104738
+ if( x<10 ) return 1;
104739
+ n = x%10;
104740
+ x /= 10;
104741
+ if( n>=5 ) n -= 2;
104742
+ else if( n>=1 ) n -= 1;
104743
+ if( x>=3 ) return (n+8)<<(x-3);
104744
+ return (n+8)>>(3-x);
104745
+}
104746
+
104747
+/*
104748
+** Return the estimated number of output rows from a WHERE clause
104749
+*/
104750
+SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
104751
+ return whereCostToInt(pWInfo->nRowOut);
104752
+}
104753
+
104754
+/*
104755
+** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
104756
+** WHERE clause returns outputs for DISTINCT processing.
104757
+*/
104758
+SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
104759
+ return pWInfo->eDistinct;
104760
+}
104761
+
104762
+/*
104763
+** Return TRUE if the WHERE clause returns rows in ORDER BY order.
104764
+** Return FALSE if the output needs to be sorted.
104765
+*/
104766
+SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
104767
+ return pWInfo->bOBSat!=0;
104768
+}
104769
+
104770
+/*
104771
+** Return the VDBE address or label to jump to in order to continue
104772
+** immediately with the next row of a WHERE clause.
104773
+*/
104774
+SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
104775
+ return pWInfo->iContinue;
104776
+}
104777
+
104778
+/*
104779
+** Return the VDBE address or label to jump to in order to break
104780
+** out of a WHERE loop.
104781
+*/
104782
+SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
104783
+ return pWInfo->iBreak;
104784
+}
104785
+
104786
+/*
104787
+** Return TRUE if an UPDATE or DELETE statement can operate directly on
104788
+** the rowids returned by a WHERE clause. Return FALSE if doing an
104789
+** UPDATE or DELETE might change subsequent WHERE clause results.
104790
+*/
104791
+SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
104792
+ return pWInfo->okOnePass;
104676104793
}
104677104794
104678104795
/*
104679104796
** Initialize a preallocated WhereClause structure.
104680104797
*/
104681104798
static void whereClauseInit(
104682104799
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 */
104800
+ WhereInfo *pWInfo /* The WHERE processing context */
104686104801
){
104687
- pWC->pParse = pParse;
104688
- pWC->pMaskSet = pMaskSet;
104802
+ pWC->pWInfo = pWInfo;
104689104803
pWC->pOuter = 0;
104690104804
pWC->nTerm = 0;
104691104805
pWC->nSlot = ArraySize(pWC->aStatic);
104692104806
pWC->a = pWC->aStatic;
104693
- pWC->wctrlFlags = wctrlFlags;
104694104807
}
104695104808
104696104809
/* Forward reference */
104697104810
static void whereClauseClear(WhereClause*);
104698104811
@@ -104717,11 +104830,11 @@
104717104830
** itself is not freed. This routine is the inverse of whereClauseInit().
104718104831
*/
104719104832
static void whereClauseClear(WhereClause *pWC){
104720104833
int i;
104721104834
WhereTerm *a;
104722
- sqlite3 *db = pWC->pParse->db;
104835
+ sqlite3 *db = pWC->pWInfo->pParse->db;
104723104836
for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104724104837
if( a->wtFlags & TERM_DYNAMIC ){
104725104838
sqlite3ExprDelete(db, a->pExpr);
104726104839
}
104727104840
if( a->wtFlags & TERM_ORINFO ){
@@ -104758,11 +104871,11 @@
104758104871
WhereTerm *pTerm;
104759104872
int idx;
104760104873
testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
104761104874
if( pWC->nTerm>=pWC->nSlot ){
104762104875
WhereTerm *pOld = pWC->a;
104763
- sqlite3 *db = pWC->pParse->db;
104876
+ sqlite3 *db = pWC->pWInfo->pParse->db;
104764104877
pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104765104878
if( pWC->a==0 ){
104766104879
if( wtFlags & TERM_DYNAMIC ){
104767104880
sqlite3ExprDelete(db, p);
104768104881
}
@@ -104798,12 +104911,12 @@
104798104911
**
104799104912
** In the previous sentence and in the diagram, "slot[]" refers to
104800104913
** the WhereClause.a[] array. The slot[] array grows as needed to contain
104801104914
** all terms of the WHERE clause.
104802104915
*/
104803
-static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104804
- pWC->op = (u8)op;
104916
+static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
104917
+ pWC->op = op;
104805104918
if( pExpr==0 ) return;
104806104919
if( pExpr->op!=op ){
104807104920
whereClauseInsert(pWC, pExpr, 0);
104808104921
}else{
104809104922
whereSplit(pWC, pExpr->pLeft, op);
@@ -104810,13 +104923,13 @@
104810104923
whereSplit(pWC, pExpr->pRight, op);
104811104924
}
104812104925
}
104813104926
104814104927
/*
104815
-** Initialize an expression mask set (a WhereMaskSet object)
104928
+** Initialize a WhereMaskSet object
104816104929
*/
104817
-#define initMaskSet(P) memset(P, 0, sizeof(*P))
104930
+#define initMaskSet(P) (P)->n=0
104818104931
104819104932
/*
104820104933
** Return the bitmask for the given cursor number. Return 0 if
104821104934
** iCursor is not in the set.
104822104935
*/
@@ -104823,11 +104936,11 @@
104823104936
static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104824104937
int i;
104825104938
assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104826104939
for(i=0; i<pMaskSet->n; i++){
104827104940
if( pMaskSet->ix[i]==iCursor ){
104828
- return ((Bitmask)1)<<i;
104941
+ return MASKBIT(i);
104829104942
}
104830104943
}
104831104944
return 0;
104832104945
}
104833104946
@@ -104843,22 +104956,13 @@
104843104956
assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104844104957
pMaskSet->ix[pMaskSet->n++] = iCursor;
104845104958
}
104846104959
104847104960
/*
104848
-** This routine walks (recursively) an expression tree and generates
104961
+** These routine walk (recursively) an expression tree and generates
104849104962
** a bitmask indicating which tables are used in that expression
104850104963
** 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.
104860104964
*/
104861104965
static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104862104966
static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104863104967
static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104864104968
Bitmask mask = 0;
@@ -104908,11 +105012,11 @@
104908105012
}
104909105013
104910105014
/*
104911105015
** Return TRUE if the given operator is one of the operators that is
104912105016
** allowed for an indexable WHERE clause term. The allowed operators are
104913
-** "=", "<", ">", "<=", ">=", and "IN".
105017
+** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
104914105018
**
104915105019
** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104916105020
** of one of the following forms: column = expression column > expression
104917105021
** column >= expression column < expression column <= expression
104918105022
** expression = column expression > column expression >= column
@@ -104935,14 +105039,13 @@
104935105039
/*
104936105040
** Commute a comparison operator. Expressions of the form "X op Y"
104937105041
** are converted into "Y op X".
104938105042
**
104939105043
** 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
105044
+** collating sequence, then COLLATE operators are adjusted to ensure
105045
+** that the collating sequence does not change. For example:
105046
+** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
104944105047
** the left hand side of a comparison overrides any collation sequence
104945105048
** attached to the right. For the same reason the EP_Collate flag
104946105049
** is not commuted.
104947105050
*/
104948105051
static void exprCommute(Parse *pParse, Expr *pExpr){
@@ -104994,10 +105097,134 @@
104994105097
assert( op!=TK_LE || c==WO_LE );
104995105098
assert( op!=TK_GT || c==WO_GT );
104996105099
assert( op!=TK_GE || c==WO_GE );
104997105100
return c;
104998105101
}
105102
+
105103
+/*
105104
+** Advance to the next WhereTerm that matches according to the criteria
105105
+** established when the pScan object was initialized by whereScanInit().
105106
+** Return NULL if there are no more matching WhereTerms.
105107
+*/
105108
+WhereTerm *whereScanNext(WhereScan *pScan){
105109
+ int iCur; /* The cursor on the LHS of the term */
105110
+ int iColumn; /* The column on the LHS of the term. -1 for IPK */
105111
+ Expr *pX; /* An expression being tested */
105112
+ WhereClause *pWC; /* Shorthand for pScan->pWC */
105113
+ WhereTerm *pTerm; /* The term being tested */
105114
+ int k = pScan->k; /* Where to start scanning */
105115
+
105116
+ while( pScan->iEquiv<=pScan->nEquiv ){
105117
+ iCur = pScan->aEquiv[pScan->iEquiv-2];
105118
+ iColumn = pScan->aEquiv[pScan->iEquiv-1];
105119
+ while( (pWC = pScan->pWC)!=0 ){
105120
+ for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
105121
+ if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
105122
+ if( (pTerm->eOperator & WO_EQUIV)!=0
105123
+ && pScan->nEquiv<ArraySize(pScan->aEquiv)
105124
+ ){
105125
+ int j;
105126
+ pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105127
+ assert( pX->op==TK_COLUMN );
105128
+ for(j=0; j<pScan->nEquiv; j+=2){
105129
+ if( pScan->aEquiv[j]==pX->iTable
105130
+ && pScan->aEquiv[j+1]==pX->iColumn ){
105131
+ break;
105132
+ }
105133
+ }
105134
+ if( j==pScan->nEquiv ){
105135
+ pScan->aEquiv[j] = pX->iTable;
105136
+ pScan->aEquiv[j+1] = pX->iColumn;
105137
+ pScan->nEquiv += 2;
105138
+ }
105139
+ }
105140
+ if( (pTerm->eOperator & pScan->opMask)!=0 ){
105141
+ /* Verify the affinity and collating sequence match */
105142
+ if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
105143
+ CollSeq *pColl;
105144
+ Parse *pParse = pWC->pWInfo->pParse;
105145
+ pX = pTerm->pExpr;
105146
+ if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
105147
+ continue;
105148
+ }
105149
+ assert(pX->pLeft);
105150
+ pColl = sqlite3BinaryCompareCollSeq(pParse,
105151
+ pX->pLeft, pX->pRight);
105152
+ if( pColl==0 ) pColl = pParse->db->pDfltColl;
105153
+ if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
105154
+ continue;
105155
+ }
105156
+ }
105157
+ if( (pTerm->eOperator & WO_EQ)!=0
105158
+ && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
105159
+ && pX->iTable==pScan->aEquiv[0]
105160
+ && pX->iColumn==pScan->aEquiv[1]
105161
+ ){
105162
+ continue;
105163
+ }
105164
+ pScan->k = k+1;
105165
+ return pTerm;
105166
+ }
105167
+ }
105168
+ }
105169
+ pScan->pWC = pScan->pWC->pOuter;
105170
+ k = 0;
105171
+ }
105172
+ pScan->pWC = pScan->pOrigWC;
105173
+ k = 0;
105174
+ pScan->iEquiv += 2;
105175
+ }
105176
+ return 0;
105177
+}
105178
+
105179
+/*
105180
+** Initialize a WHERE clause scanner object. Return a pointer to the
105181
+** first match. Return NULL if there are no matches.
105182
+**
105183
+** The scanner will be searching the WHERE clause pWC. It will look
105184
+** for terms of the form "X <op> <expr>" where X is column iColumn of table
105185
+** iCur. The <op> must be one of the operators described by opMask.
105186
+**
105187
+** If the search is for X and the WHERE clause contains terms of the
105188
+** form X=Y then this routine might also return terms of the form
105189
+** "Y <op> <expr>". The number of levels of transitivity is limited,
105190
+** but is enough to handle most commonly occurring SQL statements.
105191
+**
105192
+** If X is not the INTEGER PRIMARY KEY then X must be compatible with
105193
+** index pIdx.
105194
+*/
105195
+WhereTerm *whereScanInit(
105196
+ WhereScan *pScan, /* The WhereScan object being initialized */
105197
+ WhereClause *pWC, /* The WHERE clause to be scanned */
105198
+ int iCur, /* Cursor to scan for */
105199
+ int iColumn, /* Column to scan for */
105200
+ u32 opMask, /* Operator(s) to scan for */
105201
+ Index *pIdx /* Must be compatible with this index */
105202
+){
105203
+ int j;
105204
+
105205
+ /* memset(pScan, 0, sizeof(*pScan)); */
105206
+ pScan->pOrigWC = pWC;
105207
+ pScan->pWC = pWC;
105208
+ if( pIdx && iColumn>=0 ){
105209
+ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
105210
+ for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
105211
+ if( NEVER(j>=pIdx->nColumn) ) return 0;
105212
+ }
105213
+ pScan->zCollName = pIdx->azColl[j];
105214
+ }else{
105215
+ pScan->idxaff = 0;
105216
+ pScan->zCollName = 0;
105217
+ }
105218
+ pScan->opMask = opMask;
105219
+ pScan->k = 0;
105220
+ pScan->aEquiv[0] = iCur;
105221
+ pScan->aEquiv[1] = iColumn;
105222
+ pScan->nEquiv = 2;
105223
+ pScan->iEquiv = 2;
105224
+ return whereScanNext(pScan);
105225
+}
104999105226
105000105227
/*
105001105228
** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105002105229
** where X is a reference to the iColumn of table iCur and <op> is one of
105003105230
** the WO_xx operator codes specified by the op parameter.
@@ -105026,98 +105253,32 @@
105026105253
int iColumn, /* Column number of LHS */
105027105254
Bitmask notReady, /* RHS must not overlap with this mask */
105028105255
u32 op, /* Mask of WO_xx values describing operator */
105029105256
Index *pIdx /* Must be compatible with this index, if not NULL */
105030105257
){
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:
105258
+ WhereTerm *pResult = 0;
105259
+ WhereTerm *p;
105260
+ WhereScan scan;
105261
+
105262
+ p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
105263
+ while( p ){
105264
+ if( (p->prereqRight & notReady)==0 ){
105265
+ if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
105266
+ return p;
105267
+ }
105268
+ if( pResult==0 ) pResult = p;
105269
+ }
105270
+ p = whereScanNext(&scan);
105271
+ }
105109105272
return pResult;
105110105273
}
105111105274
105112105275
/* Forward reference */
105113105276
static void exprAnalyze(SrcList*, WhereClause*, int);
105114105277
105115105278
/*
105116105279
** Call exprAnalyze on all terms in a WHERE clause.
105117
-**
105118
-**
105119105280
*/
105120105281
static void exprAnalyzeAll(
105121105282
SrcList *pTabList, /* the FROM clause */
105122105283
WhereClause *pWC /* the WHERE clause to be analyzed */
105123105284
){
@@ -105345,15 +105506,15 @@
105345105506
static void exprAnalyzeOrTerm(
105346105507
SrcList *pSrc, /* the FROM clause */
105347105508
WhereClause *pWC, /* the complete WHERE clause */
105348105509
int idxTerm /* Index of the OR-term to be analyzed */
105349105510
){
105350
- Parse *pParse = pWC->pParse; /* Parser context */
105511
+ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105512
+ Parse *pParse = pWInfo->pParse; /* Parser context */
105351105513
sqlite3 *db = pParse->db; /* Database connection */
105352105514
WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
105353105515
Expr *pExpr = pTerm->pExpr; /* The expression of the term */
105354
- WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
105355105516
int i; /* Loop counters */
105356105517
WhereClause *pOrWc; /* Breakup of pTerm into subterms */
105357105518
WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
105358105519
WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
105359105520
Bitmask chngToIN; /* Tables that might satisfy case 1 */
@@ -105368,11 +105529,11 @@
105368105529
assert( pExpr->op==TK_OR );
105369105530
pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105370105531
if( pOrInfo==0 ) return;
105371105532
pTerm->wtFlags |= TERM_ORINFO;
105372105533
pOrWc = &pOrInfo->wc;
105373
- whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105534
+ whereClauseInit(pOrWc, pWInfo);
105374105535
whereSplit(pOrWc, pExpr, TK_OR);
105375105536
exprAnalyzeAll(pSrc, pOrWc);
105376105537
if( db->mallocFailed ) return;
105377105538
assert( pOrWc->nTerm>=2 );
105378105539
@@ -105394,20 +105555,20 @@
105394105555
Bitmask b = 0;
105395105556
pOrTerm->u.pAndInfo = pAndInfo;
105396105557
pOrTerm->wtFlags |= TERM_ANDINFO;
105397105558
pOrTerm->eOperator = WO_AND;
105398105559
pAndWC = &pAndInfo->wc;
105399
- whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105560
+ whereClauseInit(pAndWC, pWC->pWInfo);
105400105561
whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105401105562
exprAnalyzeAll(pSrc, pAndWC);
105402105563
pAndWC->pOuter = pWC;
105403105564
testcase( db->mallocFailed );
105404105565
if( !db->mallocFailed ){
105405105566
for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105406105567
assert( pAndTerm->pExpr );
105407105568
if( allowedOp(pAndTerm->pExpr->op) ){
105408
- b |= getMask(pMaskSet, pAndTerm->leftCursor);
105569
+ b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
105409105570
}
105410105571
}
105411105572
}
105412105573
indexable &= b;
105413105574
}
@@ -105414,14 +105575,14 @@
105414105575
}else if( pOrTerm->wtFlags & TERM_COPIED ){
105415105576
/* Skip this term for now. We revisit it when we process the
105416105577
** corresponding TERM_VIRTUAL term */
105417105578
}else{
105418105579
Bitmask b;
105419
- b = getMask(pMaskSet, pOrTerm->leftCursor);
105580
+ b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
105420105581
if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105421105582
WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105422
- b |= getMask(pMaskSet, pOther->leftCursor);
105583
+ b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
105423105584
}
105424105585
indexable &= b;
105425105586
if( (pOrTerm->eOperator & WO_EQ)==0 ){
105426105587
chngToIN = 0;
105427105588
}else{
@@ -105479,11 +105640,11 @@
105479105640
/* This is the 2-bit case and we are on the second iteration and
105480105641
** current term is from the first iteration. So skip this term. */
105481105642
assert( j==1 );
105482105643
continue;
105483105644
}
105484
- if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
105645
+ if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
105485105646
/* This term must be of the form t1.a==t2.b where t2 is in the
105486105647
** chngToIN set but t1 is not. This term will be either preceeded
105487105648
** or follwed by an inverted copy (t2.b==t1.a). Skip this term
105488105649
** and use its inversion. */
105489105650
testcase( pOrTerm->wtFlags & TERM_COPIED );
@@ -105498,11 +105659,11 @@
105498105659
if( i<0 ){
105499105660
/* No candidate table+column was found. This can only occur
105500105661
** on the second iteration */
105501105662
assert( j==1 );
105502105663
assert( IsPowerOfTwo(chngToIN) );
105503
- assert( chngToIN==getMask(pMaskSet, iCursor) );
105664
+ assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
105504105665
break;
105505105666
}
105506105667
testcase( j==1 );
105507105668
105508105669
/* We have found a candidate table and column. Check to see if that
@@ -105547,11 +105708,11 @@
105547105708
if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105548105709
assert( pOrTerm->eOperator & WO_EQ );
105549105710
assert( pOrTerm->leftCursor==iCursor );
105550105711
assert( pOrTerm->u.leftColumn==iColumn );
105551105712
pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105552
- pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
105713
+ pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
105553105714
pLeft = pOrTerm->pExpr->pLeft;
105554105715
}
105555105716
assert( pLeft!=0 );
105556105717
pDup = sqlite3ExprDup(db, pLeft, 0);
105557105718
pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
@@ -105596,10 +105757,11 @@
105596105757
static void exprAnalyze(
105597105758
SrcList *pSrc, /* the FROM clause */
105598105759
WhereClause *pWC, /* the WHERE clause */
105599105760
int idxTerm /* Index of the term to be analyzed */
105600105761
){
105762
+ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105601105763
WhereTerm *pTerm; /* The term to be analyzed */
105602105764
WhereMaskSet *pMaskSet; /* Set of table index masks */
105603105765
Expr *pExpr; /* The expression to be analyzed */
105604105766
Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
105605105767
Bitmask prereqAll; /* Prerequesites of pExpr */
@@ -105606,18 +105768,18 @@
105606105768
Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
105607105769
Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
105608105770
int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
105609105771
int noCase = 0; /* LIKE/GLOB distinguishes case */
105610105772
int op; /* Top-level operator. pExpr->op */
105611
- Parse *pParse = pWC->pParse; /* Parsing context */
105773
+ Parse *pParse = pWInfo->pParse; /* Parsing context */
105612105774
sqlite3 *db = pParse->db; /* Database connection */
105613105775
105614105776
if( db->mallocFailed ){
105615105777
return;
105616105778
}
105617105779
pTerm = &pWC->a[idxTerm];
105618
- pMaskSet = pWC->pMaskSet;
105780
+ pMaskSet = &pWInfo->sMaskSet;
105619105781
pExpr = pTerm->pExpr;
105620105782
assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105621105783
prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105622105784
op = pExpr->op;
105623105785
if( op==TK_IN ){
@@ -105891,15 +106053,12 @@
105891106053
*/
105892106054
pTerm->prereqRight |= extraRight;
105893106055
}
105894106056
105895106057
/*
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.
106058
+** This function searches pList for a entry that matches the iCol-th column
106059
+** of index pIdx.
105901106060
**
105902106061
** If such an expression is found, its index in pList->a[] is returned. If
105903106062
** no expression is found, -1 is returned.
105904106063
*/
105905106064
static int findIndexCol(
@@ -105925,82 +106084,23 @@
105925106084
}
105926106085
}
105927106086
105928106087
return -1;
105929106088
}
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
-
105990106089
105991106090
/*
105992106091
** 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.
106092
+** is redundant.
106093
+**
106094
+** A DISTINCT list is redundant if the database contains some subset of
106095
+** columns that are unique and non-null.
105996106096
*/
105997106097
static int isDistinctRedundant(
105998
- Parse *pParse,
105999
- SrcList *pTabList,
106000
- WhereClause *pWC,
106001
- ExprList *pDistinct
106098
+ Parse *pParse, /* Parsing context */
106099
+ SrcList *pTabList, /* The FROM clause */
106100
+ WhereClause *pWC, /* The WHERE clause */
106101
+ ExprList *pDistinct /* The result set that needs to be DISTINCT */
106002106102
){
106003106103
Table *pTab;
106004106104
Index *pIdx;
106005106105
int i;
106006106106
int iBase;
@@ -106051,35 +106151,90 @@
106051106151
}
106052106152
}
106053106153
106054106154
return 0;
106055106155
}
106156
+
106157
+/*
106158
+** The (an approximate) sum of two WhereCosts. This computation is
106159
+** not a simple "+" operator because WhereCost is stored as a logarithmic
106160
+** value.
106161
+**
106162
+*/
106163
+static WhereCost whereCostAdd(WhereCost a, WhereCost b){
106164
+ static const unsigned char x[] = {
106165
+ 10, 10, /* 0,1 */
106166
+ 9, 9, /* 2,3 */
106167
+ 8, 8, /* 4,5 */
106168
+ 7, 7, 7, /* 6,7,8 */
106169
+ 6, 6, 6, /* 9,10,11 */
106170
+ 5, 5, 5, /* 12-14 */
106171
+ 4, 4, 4, 4, /* 15-18 */
106172
+ 3, 3, 3, 3, 3, 3, /* 19-24 */
106173
+ 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
106174
+ };
106175
+ if( a>=b ){
106176
+ if( a>b+49 ) return a;
106177
+ if( a>b+31 ) return a+1;
106178
+ return a+x[a-b];
106179
+ }else{
106180
+ if( b>a+49 ) return b;
106181
+ if( b>a+31 ) return b+1;
106182
+ return b+x[b-a];
106183
+ }
106184
+}
106056106185
106057106186
/*
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.
106187
+** Convert an integer into a WhereCost. In other words, compute a
106188
+** good approximatation for 10*log2(x).
106063106189
*/
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;
106190
+static WhereCost whereCost(tRowcnt x){
106191
+ static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
106192
+ WhereCost y = 40;
106193
+ if( x<8 ){
106194
+ if( x<2 ) return 0;
106195
+ while( x<8 ){ y -= 10; x <<= 1; }
106196
+ }else{
106197
+ while( x>255 ){ y += 40; x >>= 4; }
106198
+ while( x>15 ){ y += 10; x >>= 1; }
106199
+ }
106200
+ return a[x&7] + y - 10;
106201
+}
106202
+
106203
+#ifndef SQLITE_OMIT_VIRTUALTABLE
106204
+/*
106205
+** Convert a double (as received from xBestIndex of a virtual table)
106206
+** into a WhereCost. In other words, compute an approximation for
106207
+** 10*log2(x).
106208
+*/
106209
+static WhereCost whereCostFromDouble(double x){
106210
+ u64 a;
106211
+ WhereCost e;
106212
+ assert( sizeof(x)==8 && sizeof(a)==8 );
106213
+ if( x<=1 ) return 0;
106214
+ if( x<=2000000000 ) return whereCost((tRowcnt)x);
106215
+ memcpy(&a, &x, 8);
106216
+ e = (a>>52) - 1022;
106217
+ return e*10;
106218
+}
106219
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
106220
+
106221
+/*
106222
+** Estimate the logarithm of the input value to base 2.
106223
+*/
106224
+static WhereCost estLog(WhereCost N){
106225
+ WhereCost x = whereCost(N);
106226
+ return x>33 ? x - 33 : 0;
106072106227
}
106073106228
106074106229
/*
106075106230
** Two routines for printing the content of an sqlite3_index_info
106076106231
** structure. Used for testing and debugging only. If neither
106077106232
** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106078106233
** are no-ops.
106079106234
*/
106080
-#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
106235
+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
106081106236
static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106082106237
int i;
106083106238
if( !sqlite3WhereTrace ) return;
106084106239
for(i=0; i<p->nConstraint; i++){
106085106240
sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
@@ -106113,111 +106268,10 @@
106113106268
#else
106114106269
#define TRACE_IDX_INPUTS(A)
106115106270
#define TRACE_IDX_OUTPUTS(A)
106116106271
#endif
106117106272
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
-
106219106273
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106220106274
/*
106221106275
** Return TRUE if the WHERE clause term pTerm is of a form where it
106222106276
** could be used with an index to access pSrc, assuming an appropriate
106223106277
** index existed.
@@ -106229,92 +106283,17 @@
106229106283
){
106230106284
char aff;
106231106285
if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106232106286
if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106233106287
if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106288
+ if( pTerm->u.leftColumn<0 ) return 0;
106234106289
aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106235106290
if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106236106291
return 1;
106237106292
}
106238106293
#endif
106239106294
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
-
106316106295
106317106296
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106318106297
/*
106319106298
** Generate code to construct the Index object for an automatic index
106320106299
** and to set up the WhereLevel object pLevel so that the code generator
@@ -106340,10 +106319,11 @@
106340106319
int regRecord; /* Register holding an index record */
106341106320
int n; /* Column counter */
106342106321
int i; /* Loop counter */
106343106322
int mxBitCol; /* Maximum column in pSrc->colUsed */
106344106323
CollSeq *pColl; /* Collating sequence to on a column */
106324
+ WhereLoop *pLoop; /* The Loop object */
106345106325
Bitmask idxCols; /* Bitmap of columns used for indexing */
106346106326
Bitmask extraCols; /* Bitmap of additional columns */
106347106327
106348106328
/* Generate code to skip over the creation and initialization of the
106349106329
** transient index on 2nd and subsequent iterations of the loop. */
@@ -106354,54 +106334,58 @@
106354106334
/* Count the number of columns that will be added to the index
106355106335
** and used to match WHERE clause constraints */
106356106336
nColumn = 0;
106357106337
pTable = pSrc->pTab;
106358106338
pWCEnd = &pWC->a[pWC->nTerm];
106339
+ pLoop = pLevel->pWLoop;
106359106340
idxCols = 0;
106360106341
for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106361106342
if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106362106343
int iCol = pTerm->u.leftColumn;
106363
- Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106344
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106364106345
testcase( iCol==BMS );
106365106346
testcase( iCol==BMS-1 );
106366106347
if( (idxCols & cMask)==0 ){
106367
- nColumn++;
106348
+ if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
106349
+ pLoop->aLTerm[nColumn++] = pTerm;
106368106350
idxCols |= cMask;
106369106351
}
106370106352
}
106371106353
}
106372106354
assert( nColumn>0 );
106373
- pLevel->plan.nEq = nColumn;
106355
+ pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
106356
+ pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
106357
+ | WHERE_TEMP_INDEX;
106374106358
106375106359
/* Count the number of additional columns needed to create a
106376106360
** covering index. A "covering index" is an index that contains all
106377106361
** columns that are needed by the query. With a covering index, the
106378106362
** original table never needs to be accessed. Automatic indices must
106379106363
** be a covering index because the index will not be updated if the
106380106364
** original table changes and the index and table cannot both be used
106381106365
** if they go out of sync.
106382106366
*/
106383
- extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
106367
+ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
106384106368
mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106385106369
testcase( pTable->nCol==BMS-1 );
106386106370
testcase( pTable->nCol==BMS-2 );
106387106371
for(i=0; i<mxBitCol; i++){
106388
- if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
106372
+ if( extraCols & MASKBIT(i) ) nColumn++;
106389106373
}
106390
- if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106374
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){
106391106375
nColumn += pTable->nCol - BMS + 1;
106392106376
}
106393
- pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
106377
+ pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
106394106378
106395106379
/* Construct the Index object to describe this index */
106396106380
nByte = sizeof(Index);
106397106381
nByte += nColumn*sizeof(int); /* Index.aiColumn */
106398106382
nByte += nColumn*sizeof(char*); /* Index.azColl */
106399106383
nByte += nColumn; /* Index.aSortOrder */
106400106384
pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106401106385
if( pIdx==0 ) return;
106402
- pLevel->plan.u.pIdx = pIdx;
106386
+ pLoop->u.btree.pIndex = pIdx;
106403106387
pIdx->azColl = (char**)&pIdx[1];
106404106388
pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106405106389
pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106406106390
pIdx->zName = "auto-index";
106407106391
pIdx->nColumn = nColumn;
@@ -106409,11 +106393,13 @@
106409106393
n = 0;
106410106394
idxCols = 0;
106411106395
for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106412106396
if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106413106397
int iCol = pTerm->u.leftColumn;
106414
- Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106398
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106399
+ testcase( iCol==BMS-1 );
106400
+ testcase( iCol==BMS );
106415106401
if( (idxCols & cMask)==0 ){
106416106402
Expr *pX = pTerm->pExpr;
106417106403
idxCols |= cMask;
106418106404
pIdx->aiColumn[n] = pTerm->u.leftColumn;
106419106405
pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
@@ -106420,22 +106406,22 @@
106420106406
pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106421106407
n++;
106422106408
}
106423106409
}
106424106410
}
106425
- assert( (u32)n==pLevel->plan.nEq );
106411
+ assert( (u32)n==pLoop->u.btree.nEq );
106426106412
106427106413
/* Add additional columns needed to make the automatic index into
106428106414
** a covering index */
106429106415
for(i=0; i<mxBitCol; i++){
106430
- if( extraCols & (((Bitmask)1)<<i) ){
106416
+ if( extraCols & MASKBIT(i) ){
106431106417
pIdx->aiColumn[n] = i;
106432106418
pIdx->azColl[n] = "BINARY";
106433106419
n++;
106434106420
}
106435106421
}
106436
- if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106422
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){
106437106423
for(i=BMS-1; i<pTable->nCol; i++){
106438106424
pIdx->aiColumn[n] = i;
106439106425
pIdx->azColl[n] = "BINARY";
106440106426
n++;
106441106427
}
@@ -106443,10 +106429,11 @@
106443106429
assert( n==nColumn );
106444106430
106445106431
/* Create the automatic index */
106446106432
pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106447106433
assert( pLevel->iIdxCur>=0 );
106434
+ pLevel->iIdxCur = pParse->nTab++;
106448106435
sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106449106436
(char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106450106437
VdbeComment((v, "for %s", pTable->zName));
106451106438
106452106439
/* Fill the automatic index with content */
@@ -106469,26 +106456,25 @@
106469106456
/*
106470106457
** Allocate and populate an sqlite3_index_info structure. It is the
106471106458
** responsibility of the caller to eventually release the structure
106472106459
** by passing the pointer returned by this function to sqlite3_free().
106473106460
*/
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;
106461
+static sqlite3_index_info *allocateIndexInfo(
106462
+ Parse *pParse,
106463
+ WhereClause *pWC,
106464
+ struct SrcList_item *pSrc,
106465
+ ExprList *pOrderBy
106466
+){
106479106467
int i, j;
106480106468
int nTerm;
106481106469
struct sqlite3_index_constraint *pIdxCons;
106482106470
struct sqlite3_index_orderby *pIdxOrderBy;
106483106471
struct sqlite3_index_constraint_usage *pUsage;
106484106472
WhereTerm *pTerm;
106485106473
int nOrderBy;
106486106474
sqlite3_index_info *pIdxInfo;
106487106475
106488
- WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
106489
-
106490106476
/* Count the number of possible WHERE clause constraints referring
106491106477
** to this virtual table */
106492106478
for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106493106479
if( pTerm->leftCursor != pSrc->iCursor ) continue;
106494106480
assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
@@ -106520,11 +106506,10 @@
106520106506
pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106521106507
+ (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106522106508
+ sizeof(*pIdxOrderBy)*nOrderBy );
106523106509
if( pIdxInfo==0 ){
106524106510
sqlite3ErrorMsg(pParse, "out of memory");
106525
- /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106526106511
return 0;
106527106512
}
106528106513
106529106514
/* Initialize the structure. The sqlite3_index_info structure contains
106530106515
** many fields that are declared "const" to prevent xBestIndex from
@@ -106576,12 +106561,12 @@
106576106561
}
106577106562
106578106563
/*
106579106564
** The table object reference passed as the second argument to this function
106580106565
** 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.
106566
+** method of the virtual table with the sqlite3_index_info object that
106567
+** comes in as the 3rd argument to this function.
106583106568
**
106584106569
** If an error occurs, pParse is populated with an error message and a
106585106570
** non-zero value is returned. Otherwise, 0 is returned and the output
106586106571
** part of the sqlite3_index_info structure is left populated.
106587106572
**
@@ -106592,11 +106577,10 @@
106592106577
static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106593106578
sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106594106579
int i;
106595106580
int rc;
106596106581
106597
- WHERETRACE(("xBestIndex for %s\n", pTab->zName));
106598106582
TRACE_IDX_INPUTS(p);
106599106583
rc = pVtab->pModule->xBestIndex(pVtab, p);
106600106584
TRACE_IDX_OUTPUTS(p);
106601106585
106602106586
if( rc!=SQLITE_OK ){
@@ -106618,211 +106602,12 @@
106618106602
}
106619106603
}
106620106604
106621106605
return pParse->nErr;
106622106606
}
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 */
106607
+#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
106608
+
106824106609
106825106610
#ifdef SQLITE_ENABLE_STAT3
106826106611
/*
106827106612
** Estimate the location of a particular key among all keys in an
106828106613
** index. Store the results in aStat as follows:
@@ -107060,11 +106845,11 @@
107060106845
Parse *pParse, /* Parsing & code generating context */
107061106846
Index *p, /* The index containing the range-compared column; "x" */
107062106847
int nEq, /* index into p->aCol[] of the range-compared column */
107063106848
WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
107064106849
WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
107065
- double *pRangeDiv /* OUT: Reduce search space by this divisor */
106850
+ WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
107066106851
){
107067106852
int rc = SQLITE_OK;
107068106853
107069106854
#ifdef SQLITE_ENABLE_STAT3
107070106855
@@ -107098,29 +106883,35 @@
107098106883
if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
107099106884
}
107100106885
sqlite3ValueFree(pRangeVal);
107101106886
}
107102106887
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);
106888
+ WhereCost iBase = whereCost(p->aiRowEst[0]);
106889
+ if( iUpper>iLower ){
106890
+ iBase -= whereCost(iUpper - iLower);
107107106891
}
107108
- WHERETRACE(("range scan regions: %u..%u div=%g\n",
107109
- (u32)iLower, (u32)iUpper, *pRangeDiv));
106892
+ *pRangeDiv = iBase;
106893
+ WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
106894
+ (u32)iLower, (u32)iUpper, *pRangeDiv));
107110106895
return SQLITE_OK;
107111106896
}
107112106897
}
107113106898
#else
107114106899
UNUSED_PARAMETER(pParse);
107115106900
UNUSED_PARAMETER(p);
107116106901
UNUSED_PARAMETER(nEq);
107117106902
#endif
107118106903
assert( pLower || pUpper );
107119
- *pRangeDiv = (double)1;
107120
- if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
107121
- if( pUpper ) *pRangeDiv *= (double)4;
106904
+ *pRangeDiv = 0;
106905
+ /* TUNING: Each inequality constraint reduces the search space 4-fold.
106906
+ ** A BETWEEN operator, therefore, reduces the search space 16-fold */
106907
+ if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
106908
+ *pRangeDiv += 20; assert( 20==whereCost(4) );
106909
+ }
106910
+ if( pUpper ){
106911
+ *pRangeDiv += 20; assert( 20==whereCost(4) );
106912
+ }
107122106913
return rc;
107123106914
}
107124106915
107125106916
#ifdef SQLITE_ENABLE_STAT3
107126106917
/*
@@ -107142,11 +106933,11 @@
107142106933
*/
107143106934
static int whereEqualScanEst(
107144106935
Parse *pParse, /* Parsing & code generating context */
107145106936
Index *p, /* The index whose left-most column is pTerm */
107146106937
Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
107147
- double *pnRow /* Write the revised row estimate here */
106938
+ tRowcnt *pnRow /* Write the revised row estimate here */
107148106939
){
107149106940
sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
107150106941
u8 aff; /* Column affinity */
107151106942
int rc; /* Subfunction return code */
107152106943
tRowcnt a[2]; /* Statistics */
@@ -107161,11 +106952,11 @@
107161106952
pRhs = sqlite3ValueNew(pParse->db);
107162106953
}
107163106954
if( pRhs==0 ) return SQLITE_NOTFOUND;
107164106955
rc = whereKeyStats(pParse, p, pRhs, 0, a);
107165106956
if( rc==SQLITE_OK ){
107166
- WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
106957
+ WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
107167106958
*pnRow = a[1];
107168106959
}
107169106960
whereEqualScanEst_cancel:
107170106961
sqlite3ValueFree(pRhs);
107171106962
return rc;
@@ -107191,16 +106982,16 @@
107191106982
*/
107192106983
static int whereInScanEst(
107193106984
Parse *pParse, /* Parsing & code generating context */
107194106985
Index *p, /* The index whose left-most column is pTerm */
107195106986
ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
107196
- double *pnRow /* Write the revised row estimate here */
106987
+ tRowcnt *pnRow /* Write the revised row estimate here */
107197106988
){
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 */
106989
+ int rc = SQLITE_OK; /* Subfunction return code */
106990
+ tRowcnt nEst; /* Number of rows for a single term */
106991
+ tRowcnt nRowEst = 0; /* New estimate of the number of rows */
106992
+ int i; /* Loop counter */
107202106993
107203106994
assert( p->aSample!=0 );
107204106995
for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107205106996
nEst = p->aiRowEst[0];
107206106997
rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
@@ -107207,888 +106998,15 @@
107207106998
nRowEst += nEst;
107208106999
}
107209107000
if( rc==SQLITE_OK ){
107210107001
if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107211107002
*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
-}
107003
+ WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
107004
+ }
107005
+ return rc;
107006
+}
107007
+#endif /* defined(SQLITE_ENABLE_STAT3) */
108090107008
108091107009
/*
108092107010
** Disable a term in the WHERE clause. Except, do not disable the term
108093107011
** if it controls a LEFT OUTER JOIN and it did not originate in the ON
108094107012
** or USING clause of that join.
@@ -108183,10 +107101,11 @@
108183107101
static int codeEqualityTerm(
108184107102
Parse *pParse, /* The parsing context */
108185107103
WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
108186107104
WhereLevel *pLevel, /* The level of the FROM clause we are working on */
108187107105
int iEq, /* Index of the equality term within this level */
107106
+ int bRev, /* True for reverse-order IN operations */
108188107107
int iTarget /* Attempt to leave results in this register */
108189107108
){
108190107109
Expr *pX = pTerm->pExpr;
108191107110
Vdbe *v = pParse->pVdbe;
108192107111
int iReg; /* Register holding results */
@@ -108200,18 +107119,17 @@
108200107119
#ifndef SQLITE_OMIT_SUBQUERY
108201107120
}else{
108202107121
int eType;
108203107122
int iTab;
108204107123
struct InLoop *pIn;
108205
- u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
107124
+ WhereLoop *pLoop = pLevel->pWLoop;
108206107125
108207
- if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
108208
- && pLevel->plan.u.pIdx->aSortOrder[iEq]
107126
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
107127
+ && pLoop->u.btree.pIndex!=0
107128
+ && pLoop->u.btree.pIndex->aSortOrder[iEq]
108209107129
){
108210107130
testcase( iEq==0 );
108211
- testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
108212
- testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
108213107131
testcase( bRev );
108214107132
bRev = !bRev;
108215107133
}
108216107134
assert( pX->op==TK_IN );
108217107135
iReg = iTarget;
@@ -108220,11 +107138,12 @@
108220107138
testcase( bRev );
108221107139
bRev = !bRev;
108222107140
}
108223107141
iTab = pX->iTable;
108224107142
sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
108225
- assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
107143
+ assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
107144
+ pLoop->wsFlags |= WHERE_IN_ABLE;
108226107145
if( pLevel->u.in.nIn==0 ){
108227107146
pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108228107147
}
108229107148
pLevel->u.in.nIn++;
108230107149
pLevel->u.in.aInLoop =
@@ -108290,33 +107209,35 @@
108290107209
** string in this example would be set to SQLITE_AFF_NONE.
108291107210
*/
108292107211
static int codeAllEqualityTerms(
108293107212
Parse *pParse, /* Parsing context */
108294107213
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 */
107214
+ int bRev, /* Reverse the order of IN operators */
108297107215
int nExtraReg, /* Number of extra registers to allocate */
108298107216
char **pzAff /* OUT: Set to point to affinity string */
108299107217
){
108300
- int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
107218
+ int nEq; /* The number of == or IN constraints to code */
108301107219
Vdbe *v = pParse->pVdbe; /* The vm under construction */
108302107220
Index *pIdx; /* The index being used for this loop */
108303
- int iCur = pLevel->iTabCur; /* The cursor of the table */
108304107221
WhereTerm *pTerm; /* A single constraint term */
107222
+ WhereLoop *pLoop; /* The WhereLoop object */
108305107223
int j; /* Loop counter */
108306107224
int regBase; /* Base register */
108307107225
int nReg; /* Number of registers to allocate */
108308107226
char *zAff; /* Affinity string to return */
108309107227
108310107228
/* 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;
107229
+ pLoop = pLevel->pWLoop;
107230
+ assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
107231
+ nEq = pLoop->u.btree.nEq;
107232
+ pIdx = pLoop->u.btree.pIndex;
107233
+ assert( pIdx!=0 );
108313107234
108314107235
/* Figure out how many memory cells we will need then allocate them.
108315107236
*/
108316107237
regBase = pParse->nMem + 1;
108317
- nReg = pLevel->plan.nEq + nExtraReg;
107238
+ nReg = pLoop->u.btree.nEq + nExtraReg;
108318107239
pParse->nMem += nReg;
108319107240
108320107241
zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
108321107242
if( !zAff ){
108322107243
pParse->db->mallocFailed = 1;
@@ -108325,18 +107246,17 @@
108325107246
/* Evaluate the equality constraints
108326107247
*/
108327107248
assert( pIdx->nColumn>=nEq );
108328107249
for(j=0; j<nEq; j++){
108329107250
int r1;
108330
- int k = pIdx->aiColumn[j];
108331
- pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
108332
- if( pTerm==0 ) break;
107251
+ pTerm = pLoop->aLTerm[j];
107252
+ assert( pTerm!=0 );
108333107253
/* The following true for indices with redundant columns.
108334107254
** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
108335107255
testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
108336107256
testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108337
- r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
107257
+ r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
108338107258
if( r1!=regBase+j ){
108339107259
if( nReg==1 ){
108340107260
sqlite3ReleaseTempReg(pParse, regBase);
108341107261
regBase = r1;
108342107262
}else{
@@ -108400,20 +107320,19 @@
108400107320
**
108401107321
** The returned pointer points to memory obtained from sqlite3DbMalloc().
108402107322
** It is the responsibility of the caller to free the buffer when it is
108403107323
** no longer required.
108404107324
*/
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;
107325
+static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
107326
+ Index *pIndex = pLoop->u.btree.pIndex;
107327
+ int nEq = pLoop->u.btree.nEq;
108409107328
int i, j;
108410107329
Column *aCol = pTab->aCol;
108411107330
int *aiColumn = pIndex->aiColumn;
108412107331
StrAccum txt;
108413107332
108414
- if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
107333
+ if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
108415107334
return 0;
108416107335
}
108417107336
sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
108418107337
txt.db = db;
108419107338
sqlite3StrAccumAppend(&txt, " (", 2);
@@ -108420,15 +107339,15 @@
108420107339
for(i=0; i<nEq; i++){
108421107340
explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
108422107341
}
108423107342
108424107343
j = i;
108425
- if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
107344
+ if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
108426107345
char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108427107346
explainAppendTerm(&txt, i++, z, ">");
108428107347
}
108429
- if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
107348
+ if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
108430107349
char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108431107350
explainAppendTerm(&txt, i, z, "<");
108432107351
}
108433107352
sqlite3StrAccumAppend(&txt, ")", 1);
108434107353
return sqlite3StrAccumFinish(&txt);
@@ -108447,24 +107366,26 @@
108447107366
int iLevel, /* Value for "level" column of output */
108448107367
int iFrom, /* Value for "from" column of output */
108449107368
u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
108450107369
){
108451107370
if( pParse->explain==2 ){
108452
- u32 flags = pLevel->plan.wsFlags;
108453107371
struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
108454107372
Vdbe *v = pParse->pVdbe; /* VM being constructed */
108455107373
sqlite3 *db = pParse->db; /* Database handle */
108456107374
char *zMsg; /* Text to add to EQP output */
108457
- sqlite3_int64 nRow; /* Expected number of rows visited by scan */
108458107375
int iId = pParse->iSelectId; /* Select id (left-most output column) */
108459107376
int isSearch; /* True for a SEARCH. False for SCAN. */
107377
+ WhereLoop *pLoop; /* The controlling WhereLoop object */
107378
+ u32 flags; /* Flags that describe this loop */
108460107379
107380
+ pLoop = pLevel->pWLoop;
107381
+ flags = pLoop->wsFlags;
108461107382
if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
108462107383
108463
- isSearch = (pLevel->plan.nEq>0)
108464
- || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
108465
- || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107384
+ isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107385
+ || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
107386
+ || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
108466107387
108467107388
zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
108468107389
if( pItem->pSelect ){
108469107390
zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
108470107391
}else{
@@ -108472,47 +107393,42 @@
108472107393
}
108473107394
108474107395
if( pItem->zAlias ){
108475107396
zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
108476107397
}
108477
- if( (flags & WHERE_INDEXED)!=0 ){
108478
- char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
107398
+ if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
107399
+ && ALWAYS(pLoop->u.btree.pIndex!=0)
107400
+ ){
107401
+ char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
108479107402
zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
108480107403
((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
108481107404
((flags & WHERE_IDX_ONLY)?"COVERING ":""),
108482107405
((flags & WHERE_TEMP_INDEX)?"":" "),
108483
- ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
107406
+ ((flags & WHERE_TEMP_INDEX)?"": pLoop->u.btree.pIndex->zName),
108484107407
zWhere
108485107408
);
108486107409
sqlite3DbFree(db, zWhere);
108487
- }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107410
+ }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
108488107411
zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
108489107412
108490
- if( flags&WHERE_ROWID_EQ ){
107413
+ if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
108491107414
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
108492107415
}else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
108493107416
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
108494107417
}else if( flags&WHERE_BTM_LIMIT ){
108495107418
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
108496
- }else if( flags&WHERE_TOP_LIMIT ){
107419
+ }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
108497107420
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
108498107421
}
108499107422
}
108500107423
#ifndef SQLITE_OMIT_VIRTUALTABLE
108501107424
else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
108502
- sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108503107425
zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
108504
- pVtabIdx->idxNum, pVtabIdx->idxStr);
107426
+ pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
108505107427
}
108506107428
#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);
107429
+ zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
108514107430
sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
108515107431
}
108516107432
}
108517107433
#else
108518107434
# define explainOneScan(u,v,w,x,y,z)
@@ -108524,19 +107440,19 @@
108524107440
** implementation described by pWInfo.
108525107441
*/
108526107442
static Bitmask codeOneLoopStart(
108527107443
WhereInfo *pWInfo, /* Complete information about the WHERE clause */
108528107444
int iLevel, /* Which level of pWInfo->a[] should be coded */
108529
- u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
108530107445
Bitmask notReady /* Which tables are currently available */
108531107446
){
108532107447
int j, k; /* Loop counters */
108533107448
int iCur; /* The VDBE cursor for the table */
108534107449
int addrNxt; /* Where to jump to continue with the next IN case */
108535107450
int omitTable; /* True if we use the index only */
108536107451
int bRev; /* True if we need to scan in reverse order */
108537107452
WhereLevel *pLevel; /* The where level to be coded */
107453
+ WhereLoop *pLoop; /* The WhereLoop object being coded */
108538107454
WhereClause *pWC; /* Decomposition of the entire WHERE clause */
108539107455
WhereTerm *pTerm; /* A WHERE clause term */
108540107456
Parse *pParse; /* Parsing context */
108541107457
Vdbe *v; /* The prepared stmt under constructions */
108542107458
struct SrcList_item *pTabItem; /* FROM clause term being coded */
@@ -108546,17 +107462,18 @@
108546107462
int iReleaseReg = 0; /* Temp register to free before returning */
108547107463
Bitmask newNotReady; /* Return value */
108548107464
108549107465
pParse = pWInfo->pParse;
108550107466
v = pParse->pVdbe;
108551
- pWC = pWInfo->pWC;
107467
+ pWC = &pWInfo->sWC;
108552107468
pLevel = &pWInfo->a[iLevel];
107469
+ pLoop = pLevel->pWLoop;
108553107470
pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108554107471
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;
107472
+ bRev = (pWInfo->revMask>>iLevel)&1;
107473
+ omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
107474
+ && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
108558107475
VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
108559107476
108560107477
/* Create labels for the "break" and "continue" instructions
108561107478
** for the current loop. Jump to addrBrk to break out of a loop.
108562107479
** Jump to cont to go immediately to the next iteration of the
@@ -108589,51 +107506,41 @@
108589107506
sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108590107507
pLevel->op = OP_Goto;
108591107508
}else
108592107509
108593107510
#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
107511
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107512
+ /* Case 1: The table is a virtual-table. Use the VFilter and VNext
108596107513
** to access the data.
108597107514
*/
108598107515
int iReg; /* P3 Value for OP_VFilter */
108599107516
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;
107517
+ int nConstraint = pLoop->nLTerm;
108606107518
108607107519
sqlite3ExprCachePush(pParse);
108608107520
iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108609107521
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;
108631107522
for(j=0; j<nConstraint; j++){
108632
- if( aUsage[j].omit ){
108633
- int iTerm = aConstraint[j].iTermOffset;
108634
- disableTerm(pLevel, &pWC->a[iTerm]);
107523
+ int iTarget = iReg+j+2;
107524
+ pTerm = pLoop->aLTerm[j];
107525
+ if( pTerm==0 ) continue;
107526
+ if( pTerm->eOperator & WO_IN ){
107527
+ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
107528
+ addrNotFound = pLevel->addrNxt;
107529
+ }else{
107530
+ sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
107531
+ }
107532
+ }
107533
+ sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
107534
+ sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
107535
+ sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
107536
+ pLoop->u.vtab.idxStr,
107537
+ pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
107538
+ pLoop->u.vtab.needFree = 0;
107539
+ for(j=0; j<nConstraint && j<16; j++){
107540
+ if( (pLoop->u.vtab.omitMask>>j)&1 ){
107541
+ disableTerm(pLevel, pLoop->aLTerm[j]);
108635107542
}
108636107543
}
108637107544
pLevel->op = OP_VNext;
108638107545
pLevel->p1 = iCur;
108639107546
pLevel->p2 = sqlite3VdbeCurrentAddr(v);
@@ -108640,41 +107547,49 @@
108640107547
sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108641107548
sqlite3ExprCachePop(pParse, 1);
108642107549
}else
108643107550
#endif /* SQLITE_OMIT_VIRTUALTABLE */
108644107551
108645
- if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
108646
- /* Case 1: We can directly reference a single row using an
107552
+ if( (pLoop->wsFlags & WHERE_IPK)!=0
107553
+ && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
107554
+ ){
107555
+ /* Case 2: We can directly reference a single row using an
108647107556
** equality comparison against the ROWID field. Or
108648107557
** we reference multiple rows using a "rowid IN (...)"
108649107558
** construct.
108650107559
*/
107560
+ assert( pLoop->u.btree.nEq==1 );
108651107561
iReleaseReg = sqlite3GetTempReg(pParse);
108652
- pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
107562
+ pTerm = pLoop->aLTerm[0];
108653107563
assert( pTerm!=0 );
108654107564
assert( pTerm->pExpr!=0 );
108655107565
assert( omitTable==0 );
108656107566
testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108657
- iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
107567
+ iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
108658107568
addrNxt = pLevel->addrNxt;
108659107569
sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108660107570
sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108661107571
sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
108662107572
sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108663107573
VdbeComment((v, "pk"));
108664107574
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.
107575
+ }else if( (pLoop->wsFlags & WHERE_IPK)!=0
107576
+ && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
107577
+ ){
107578
+ /* Case 3: We have an inequality comparison against the ROWID field.
108667107579
*/
108668107580
int testOp = OP_Noop;
108669107581
int start;
108670107582
int memEndValue = 0;
108671107583
WhereTerm *pStart, *pEnd;
108672107584
108673107585
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);
107586
+ j = 0;
107587
+ pStart = pEnd = 0;
107588
+ if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
107589
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
107590
+ assert( pStart!=0 || pEnd!=0 );
108676107591
if( bRev ){
108677107592
pTerm = pStart;
108678107593
pStart = pEnd;
108679107594
pEnd = pTerm;
108680107595
}
@@ -108725,24 +107640,20 @@
108725107640
}
108726107641
start = sqlite3VdbeCurrentAddr(v);
108727107642
pLevel->op = bRev ? OP_Prev : OP_Next;
108728107643
pLevel->p1 = iCur;
108729107644
pLevel->p2 = start;
108730
- if( pStart==0 && pEnd==0 ){
108731
- pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108732
- }else{
108733
- assert( pLevel->p5==0 );
108734
- }
107645
+ assert( pLevel->p5==0 );
108735107646
if( testOp!=OP_Noop ){
108736107647
iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108737107648
sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108738107649
sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108739107650
sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108740107651
sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108741107652
}
108742
- }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
108743
- /* Case 3: A scan using an index.
107653
+ }else if( pLoop->wsFlags & WHERE_INDEXED ){
107654
+ /* Case 4: A scan using an index.
108744107655
**
108745107656
** The WHERE clause may contain zero or more equality
108746107657
** terms ("==" or "IN" operators) that refer to the N
108747107658
** left-most columns of the index. It may also contain
108748107659
** inequality constraints (>, <, >= or <=) on the indexed
@@ -108784,12 +107695,12 @@
108784107695
static const u8 aEndOp[] = {
108785107696
OP_Noop, /* 0: (!end_constraints) */
108786107697
OP_IdxGE, /* 1: (end_constraints && !bRev) */
108787107698
OP_IdxLT /* 2: (end_constraints && bRev) */
108788107699
};
108789
- int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
108790
- int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
107700
+ int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
107701
+ int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
108791107702
int regBase; /* Base register holding constraint values */
108792107703
int r1; /* Temp register */
108793107704
WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
108794107705
WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
108795107706
int startEq; /* True if range start uses ==, >= or <= */
@@ -108801,24 +107712,23 @@
108801107712
int nExtraReg = 0; /* Number of extra registers needed */
108802107713
int op; /* Instruction opcode */
108803107714
char *zStartAff; /* Affinity for start of range constraint */
108804107715
char *zEndAff; /* Affinity for end of range constraint */
108805107716
108806
- pIdx = pLevel->plan.u.pIdx;
107717
+ pIdx = pLoop->u.btree.pIndex;
108807107718
iIdxCur = pLevel->iIdxCur;
108808
- k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
108809107719
108810107720
/* If this loop satisfies a sort order (pOrderBy) request that
108811107721
** was passed to this function to implement a "SELECT min(x) ..."
108812107722
** query, then the caller will only allow the loop to run for
108813107723
** a single iteration. This means that the first row returned
108814107724
** should not have a NULL value stored in 'x'. If column 'x' is
108815107725
** the first one after the nEq equality constraints in the index,
108816107726
** this requires some special handling.
108817107727
*/
108818
- if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
108819
- && (pLevel->plan.wsFlags&WHERE_ORDERED)
107728
+ if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
107729
+ && (pWInfo->bOBSat!=0)
108820107730
&& (pIdx->nColumn>nEq)
108821107731
){
108822107732
/* assert( pOrderBy->nExpr==1 ); */
108823107733
/* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108824107734
isMinQuery = 1;
@@ -108826,26 +107736,25 @@
108826107736
}
108827107737
108828107738
/* Find any inequality constraint terms for the start and end
108829107739
** of the range.
108830107740
*/
108831
- if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
108832
- pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
107741
+ j = nEq;
107742
+ if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
107743
+ pRangeStart = pLoop->aLTerm[j++];
108833107744
nExtraReg = 1;
108834107745
}
108835
- if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
108836
- pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
107746
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
107747
+ pRangeEnd = pLoop->aLTerm[j++];
108837107748
nExtraReg = 1;
108838107749
}
108839107750
108840107751
/* Generate code to evaluate all constraint terms using == or IN
108841107752
** and store the values of those terms in an array of registers
108842107753
** starting at regBase.
108843107754
*/
108844
- regBase = codeAllEqualityTerms(
108845
- pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
108846
- );
107755
+ regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
108847107756
zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
108848107757
addrNxt = pLevel->addrNxt;
108849107758
108850107759
/* If we are doing a reverse order scan on an ascending index, or
108851107760
** a forward order scan on a descending index, interchange the
@@ -108855,14 +107764,14 @@
108855107764
|| (bRev && pIdx->nColumn==nEq)
108856107765
){
108857107766
SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108858107767
}
108859107768
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 );
107769
+ testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
107770
+ testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
107771
+ testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
107772
+ testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
108864107773
startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108865107774
endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108866107775
start_constraints = pRangeStart || nEq>0;
108867107776
108868107777
/* Seek the index cursor to the start of the range. */
@@ -108948,13 +107857,13 @@
108948107857
/* If there are inequality constraints, check that the value
108949107858
** of the table column that the inequality contrains is not NULL.
108950107859
** If it is, jump to the next iteration of the loop.
108951107860
*/
108952107861
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 ){
107862
+ testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
107863
+ testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
107864
+ if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108956107865
sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108957107866
sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108958107867
}
108959107868
sqlite3ReleaseTempReg(pParse, r1);
108960107869
@@ -108969,28 +107878,28 @@
108969107878
}
108970107879
108971107880
/* Record the instruction used to terminate the loop. Disable
108972107881
** WHERE clause terms made redundant by the index range scan.
108973107882
*/
108974
- if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
107883
+ if( pLoop->wsFlags & WHERE_ONEROW ){
108975107884
pLevel->op = OP_Noop;
108976107885
}else if( bRev ){
108977107886
pLevel->op = OP_Prev;
108978107887
}else{
108979107888
pLevel->op = OP_Next;
108980107889
}
108981107890
pLevel->p1 = iIdxCur;
108982
- if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
107891
+ if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
108983107892
pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108984107893
}else{
108985107894
assert( pLevel->p5==0 );
108986107895
}
108987107896
}else
108988107897
108989107898
#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
107899
+ if( pLoop->wsFlags & WHERE_MULTI_OR ){
107900
+ /* Case 5: Two or more separately indexed terms connected by OR
108992107901
**
108993107902
** Example:
108994107903
**
108995107904
** CREATE TABLE t1(a,b,c,d);
108996107905
** CREATE INDEX i1 ON t1(a);
@@ -109039,11 +107948,11 @@
109039107948
int iRetInit; /* Address of regReturn init */
109040107949
int untestedTerms = 0; /* Some terms not completely tested */
109041107950
int ii; /* Loop counter */
109042107951
Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
109043107952
109044
- pTerm = pLevel->plan.u.pTerm;
107953
+ pTerm = pLoop->aLTerm[0];
109045107954
assert( pTerm!=0 );
109046107955
assert( pTerm->eOperator & WO_OR );
109047107956
assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
109048107957
pOrWc = &pTerm->u.pOrInfo->wc;
109049107958
pLevel->op = OP_Return;
@@ -109058,11 +107967,11 @@
109058107967
struct SrcList_item *origSrc; /* Original list of tables */
109059107968
nNotReady = pWInfo->nLevel - iLevel - 1;
109060107969
pOrTab = sqlite3StackAllocRaw(pParse->db,
109061107970
sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
109062107971
if( pOrTab==0 ) return notReady;
109063
- pOrTab->nAlloc = (i16)(nNotReady + 1);
107972
+ pOrTab->nAlloc = (u8)(nNotReady + 1);
109064107973
pOrTab->nSrc = pOrTab->nAlloc;
109065107974
memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
109066107975
origSrc = pWInfo->pTabList->a;
109067107976
for(k=1; k<=nNotReady; k++){
109068107977
memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
@@ -109080,11 +107989,11 @@
109080107989
** over the top of the loop into the body of it. In this case the
109081107990
** correct response for the end-of-loop code (the OP_Return) is to
109082107991
** fall through to the next instruction, just as an OP_Next does if
109083107992
** called on an uninitialized cursor.
109084107993
*/
109085
- if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107994
+ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109086107995
regRowset = ++pParse->nMem;
109087107996
regRowid = ++pParse->nMem;
109088107997
sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
109089107998
}
109090107999
iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
@@ -109131,15 +108040,15 @@
109131108040
pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
109132108041
WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
109133108042
WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
109134108043
assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
109135108044
if( pSubWInfo ){
109136
- WhereLevel *pLvl;
108045
+ WhereLoop *pSubLoop;
109137108046
explainOneScan(
109138108047
pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
109139108048
);
109140
- if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108049
+ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109141108050
int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
109142108051
int r;
109143108052
r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
109144108053
regRowid, 0);
109145108054
sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
@@ -109164,17 +108073,17 @@
109164108073
** processed or the index is the same as that used by all previous
109165108074
** terms, set pCov to the candidate covering index. Otherwise, set
109166108075
** pCov to NULL to indicate that no candidate covering index will
109167108076
** be available.
109168108077
*/
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)
108078
+ pSubLoop = pSubWInfo->a[0].pWLoop;
108079
+ assert( (pSubLoop->wsFlags & WHERE_TEMP_INDEX)==0 );
108080
+ if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
108081
+ && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
109173108082
){
109174
- assert( pLvl->iIdxCur==iCovCur );
109175
- pCov = pLvl->plan.u.pIdx;
108083
+ assert( pSubWInfo->a[0].iIdxCur==iCovCur );
108084
+ pCov = pSubLoop->u.btree.pIndex;
109176108085
}else{
109177108086
pCov = 0;
109178108087
}
109179108088
109180108089
/* Finish the loop through table entries that match term pOrTerm. */
@@ -109196,23 +108105,22 @@
109196108105
if( !untestedTerms ) disableTerm(pLevel, pTerm);
109197108106
}else
109198108107
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
109199108108
109200108109
{
109201
- /* Case 5: There is no usable index. We must do a complete
108110
+ /* Case 6: There is no usable index. We must do a complete
109202108111
** scan of the entire table.
109203108112
*/
109204108113
static const u8 aStep[] = { OP_Next, OP_Prev };
109205108114
static const u8 aStart[] = { OP_Rewind, OP_Last };
109206108115
assert( bRev==0 || bRev==1 );
109207
- assert( omitTable==0 );
109208108116
pLevel->op = aStep[bRev];
109209108117
pLevel->p1 = iCur;
109210108118
pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
109211108119
pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
109212108120
}
109213
- newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
108121
+ newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
109214108122
109215108123
/* Insert code to test every subexpression that can be completely
109216108124
** computed using the current set of tables.
109217108125
**
109218108126
** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
@@ -109258,10 +108166,12 @@
109258108166
assert( !ExprHasProperty(pE, EP_FromJoin) );
109259108167
assert( (pTerm->prereqRight & newNotReady)!=0 );
109260108168
pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
109261108169
if( pAlt==0 ) continue;
109262108170
if( pAlt->wtFlags & (TERM_CODED) ) continue;
108171
+ testcase( pAlt->eOperator & WO_EQ );
108172
+ testcase( pAlt->eOperator & WO_IN );
109263108173
VdbeNoopComment((v, "begin transitive constraint"));
109264108174
sEq = *pAlt->pExpr;
109265108175
sEq.pLeft = pE->pLeft;
109266108176
sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
109267108177
}
@@ -109290,51 +108200,1562 @@
109290108200
sqlite3ReleaseTempReg(pParse, iReleaseReg);
109291108201
109292108202
return newNotReady;
109293108203
}
109294108204
109295
-#if defined(SQLITE_TEST)
108205
+#ifdef WHERETRACE_ENABLED
109296108206
/*
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.
108207
+** Print a WhereLoop object for debugging purposes
109301108208
*/
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[] */
108209
+static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
108210
+ int nb = 1+(pTabList->nSrc+7)/8;
108211
+ struct SrcList_item *pItem = pTabList->a + p->iTab;
108212
+ Table *pTab = pItem->pTab;
108213
+ sqlite3DebugPrintf("%c %2d.%0*llx.%0*llx", p->cId,
108214
+ p->iTab, nb, p->maskSelf, nb, p->prereq);
108215
+ sqlite3DebugPrintf(" %8s",
108216
+ pItem->zAlias ? pItem->zAlias : pTab->zName);
108217
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108218
+ if( p->u.btree.pIndex ){
108219
+ const char *zName = p->u.btree.pIndex->zName;
108220
+ if( zName==0 ) zName = "ipk";
108221
+ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
108222
+ int i = sqlite3Strlen30(zName) - 1;
108223
+ while( zName[i]!='_' ) i--;
108224
+ zName += i;
108225
+ }
108226
+ sqlite3DebugPrintf(".%-12s %2d", zName, p->u.btree.nEq);
108227
+ }else{
108228
+ sqlite3DebugPrintf("%16s","");
108229
+ }
108230
+ }else{
108231
+ char *z;
108232
+ if( p->u.vtab.idxStr ){
108233
+ z = sqlite3_mprintf("(%d,\"%s\",%x)",
108234
+ p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
108235
+ }else{
108236
+ z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
108237
+ }
108238
+ sqlite3DebugPrintf(" %-15s", z);
108239
+ sqlite3_free(z);
108240
+ }
108241
+ sqlite3DebugPrintf(" fg %05x N %d", p->wsFlags, p->nLTerm);
108242
+ sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
108243
+}
108244
+#endif
109304108245
109305
-#endif /* SQLITE_TEST */
108246
+/*
108247
+** Convert bulk memory into a valid WhereLoop that can be passed
108248
+** to whereLoopClear harmlessly.
108249
+*/
108250
+static void whereLoopInit(WhereLoop *p){
108251
+ p->aLTerm = p->aLTermSpace;
108252
+ p->nLTerm = 0;
108253
+ p->nLSlot = ArraySize(p->aLTermSpace);
108254
+ p->wsFlags = 0;
108255
+}
109306108256
108257
+/*
108258
+** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
108259
+*/
108260
+static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
108261
+ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_TEMP_INDEX) ){
108262
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
108263
+ sqlite3_free(p->u.vtab.idxStr);
108264
+ p->u.vtab.needFree = 0;
108265
+ p->u.vtab.idxStr = 0;
108266
+ }else if( (p->wsFlags & WHERE_TEMP_INDEX)!=0 && p->u.btree.pIndex!=0 ){
108267
+ sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
108268
+ sqlite3DbFree(db, p->u.btree.pIndex);
108269
+ p->u.btree.pIndex = 0;
108270
+ }
108271
+ }
108272
+}
108273
+
108274
+/*
108275
+** Deallocate internal memory used by a WhereLoop object
108276
+*/
108277
+static void whereLoopClear(sqlite3 *db, WhereLoop *p){
108278
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108279
+ whereLoopClearUnion(db, p);
108280
+ whereLoopInit(p);
108281
+}
108282
+
108283
+/*
108284
+** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
108285
+*/
108286
+static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
108287
+ WhereTerm **paNew;
108288
+ if( p->nLSlot>=n ) return SQLITE_OK;
108289
+ n = (n+7)&~7;
108290
+ paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
108291
+ if( paNew==0 ) return SQLITE_NOMEM;
108292
+ memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
108293
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108294
+ p->aLTerm = paNew;
108295
+ p->nLSlot = n;
108296
+ return SQLITE_OK;
108297
+}
108298
+
108299
+/*
108300
+** Transfer content from the second pLoop into the first.
108301
+*/
108302
+static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
108303
+ if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
108304
+ whereLoopClearUnion(db, pTo);
108305
+ memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
108306
+ memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
108307
+ if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
108308
+ pFrom->u.vtab.needFree = 0;
108309
+ }else if( (pFrom->wsFlags & WHERE_TEMP_INDEX)!=0 ){
108310
+ pFrom->u.btree.pIndex = 0;
108311
+ }
108312
+ return SQLITE_OK;
108313
+}
108314
+
108315
+/*
108316
+** Delete a WhereLoop object
108317
+*/
108318
+static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
108319
+ whereLoopClear(db, p);
108320
+ sqlite3DbFree(db, p);
108321
+}
109307108322
109308108323
/*
109309108324
** Free a WhereInfo structure
109310108325
*/
109311108326
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
109312108327
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);
108328
+ whereClauseClear(&pWInfo->sWC);
108329
+ while( pWInfo->pLoops ){
108330
+ WhereLoop *p = pWInfo->pLoops;
108331
+ pWInfo->pLoops = p->pNextLoop;
108332
+ whereLoopDelete(db, p);
108333
+ }
109332108334
sqlite3DbFree(db, pWInfo);
109333108335
}
109334108336
}
109335108337
108338
+/*
108339
+** Insert or replace a WhereLoop entry using the template supplied.
108340
+**
108341
+** An existing WhereLoop entry might be overwritten if the new template
108342
+** is better and has fewer dependencies. Or the template will be ignored
108343
+** and no insert will occur if an existing WhereLoop is faster and has
108344
+** fewer dependencies than the template. Otherwise a new WhereLoop is
108345
+** added based on the template.
108346
+**
108347
+** If pBuilder->pBest is not NULL then we only care about the very
108348
+** best template and that template should be stored in pBuilder->pBest.
108349
+** If pBuilder->pBest is NULL then a list of the best templates are stored
108350
+** in pBuilder->pWInfo->pLoops.
108351
+**
108352
+** When accumulating multiple loops (when pBuilder->pBest is NULL) we
108353
+** still might overwrite similar loops with the new template if the
108354
+** template is better. Loops may be overwritten if the following
108355
+** conditions are met:
108356
+**
108357
+** (1) They have the same iTab.
108358
+** (2) They have the same iSortIdx.
108359
+** (3) The template has same or fewer dependencies than the current loop
108360
+** (4) The template has the same or lower cost than the current loop
108361
+** (5) The template uses more terms of the same index but has no additional
108362
+** dependencies
108363
+*/
108364
+static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
108365
+ WhereLoop **ppPrev, *p, *pNext = 0;
108366
+ WhereInfo *pWInfo = pBuilder->pWInfo;
108367
+ sqlite3 *db = pWInfo->pParse->db;
108368
+
108369
+ /* If pBuilder->pBest is defined, then only keep track of the single
108370
+ ** best WhereLoop. pBuilder->pBest->maskSelf==0 indicates that no
108371
+ ** prior WhereLoops have been evaluated and that the current pTemplate
108372
+ ** is therefore the first and hence the best and should be retained.
108373
+ */
108374
+ if( (p = pBuilder->pBest)!=0 ){
108375
+ if( p->maskSelf!=0 ){
108376
+ WhereCost rCost = whereCostAdd(p->rRun,p->rSetup);
108377
+ WhereCost rTemplate = whereCostAdd(pTemplate->rRun,pTemplate->rSetup);
108378
+ if( rCost < rTemplate ){
108379
+ testcase( rCost==rTemplate-1 );
108380
+ goto whereLoopInsert_noop;
108381
+ }
108382
+ if( rCost==rTemplate && (p->prereq & pTemplate->prereq)==p->prereq ){
108383
+ goto whereLoopInsert_noop;
108384
+ }
108385
+ }
108386
+#if WHERETRACE_ENABLED
108387
+ if( sqlite3WhereTrace & 0x8 ){
108388
+ sqlite3DebugPrintf(p->maskSelf==0 ? "ins-init: " : "ins-best: ");
108389
+ whereLoopPrint(pTemplate, pWInfo->pTabList);
108390
+ }
108391
+#endif
108392
+ whereLoopXfer(db, p, pTemplate);
108393
+ return SQLITE_OK;
108394
+ }
108395
+
108396
+ /* Search for an existing WhereLoop to overwrite, or which takes
108397
+ ** priority over pTemplate.
108398
+ */
108399
+ for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
108400
+ if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
108401
+ /* If either the iTab or iSortIdx values for two WhereLoop are different
108402
+ ** then those WhereLoops need to be considered separately. Neither is
108403
+ ** a candidate to replace the other. */
108404
+ continue;
108405
+ }
108406
+ /* In the current implementation, the rSetup value is either zero
108407
+ ** or the cost of building an automatic index (NlogN) and the NlogN
108408
+ ** is the same for compatible WhereLoops. */
108409
+ assert( p->rSetup==0 || pTemplate->rSetup==0
108410
+ || p->rSetup==pTemplate->rSetup );
108411
+
108412
+ /* whereLoopAddBtree() always generates and inserts the automatic index
108413
+ ** case first. Hence compatible candidate WhereLoops never have a larger
108414
+ ** rSetup. Call this SETUP-INVARIANT */
108415
+ assert( p->rSetup>=pTemplate->rSetup );
108416
+
108417
+ if( (p->prereq & pTemplate->prereq)==p->prereq
108418
+ && p->rSetup<=pTemplate->rSetup
108419
+ && p->rRun<=pTemplate->rRun
108420
+ ){
108421
+ /* This branch taken when p is equal or better than pTemplate in
108422
+ ** all of (1) dependences (2) setup-cost, and (3) run-cost. */
108423
+ assert( p->rSetup==pTemplate->rSetup );
108424
+ if( p->nLTerm<pTemplate->nLTerm
108425
+ && (p->wsFlags & WHERE_INDEXED)!=0
108426
+ && (pTemplate->wsFlags & WHERE_INDEXED)!=0
108427
+ && p->u.btree.pIndex==pTemplate->u.btree.pIndex
108428
+ && p->prereq==pTemplate->prereq
108429
+ ){
108430
+ /* Overwrite an existing WhereLoop with an similar one that uses
108431
+ ** more terms of the index */
108432
+ pNext = p->pNextLoop;
108433
+ break;
108434
+ }else{
108435
+ /* pTemplate is not helpful.
108436
+ ** Return without changing or adding anything */
108437
+ goto whereLoopInsert_noop;
108438
+ }
108439
+ }
108440
+ if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
108441
+ && p->rRun>=pTemplate->rRun
108442
+ && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
108443
+ ){
108444
+ /* Overwrite an existing WhereLoop with a better one: one that is
108445
+ ** better at one of (1) dependences, (2) setup-cost, or (3) run-cost
108446
+ ** and is no worse in any of those categories. */
108447
+ pNext = p->pNextLoop;
108448
+ break;
108449
+ }
108450
+ }
108451
+
108452
+ /* If we reach this point it means that either p[] should be overwritten
108453
+ ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
108454
+ ** WhereLoop and insert it.
108455
+ */
108456
+#if WHERETRACE_ENABLED
108457
+ if( sqlite3WhereTrace & 0x8 ){
108458
+ if( p!=0 ){
108459
+ sqlite3DebugPrintf("ins-del: ");
108460
+ whereLoopPrint(p, pWInfo->pTabList);
108461
+ }
108462
+ sqlite3DebugPrintf("ins-new: ");
108463
+ whereLoopPrint(pTemplate, pWInfo->pTabList);
108464
+ }
108465
+#endif
108466
+ if( p==0 ){
108467
+ p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
108468
+ if( p==0 ) return SQLITE_NOMEM;
108469
+ whereLoopInit(p);
108470
+ }
108471
+ whereLoopXfer(db, p, pTemplate);
108472
+ p->pNextLoop = pNext;
108473
+ *ppPrev = p;
108474
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108475
+ Index *pIndex = p->u.btree.pIndex;
108476
+ if( pIndex && pIndex->tnum==0 ){
108477
+ p->u.btree.pIndex = 0;
108478
+ }
108479
+ }
108480
+ return SQLITE_OK;
108481
+
108482
+ /* Jump here if the insert is a no-op */
108483
+whereLoopInsert_noop:
108484
+#if WHERETRACE_ENABLED
108485
+ if( sqlite3WhereTrace & 0x8 ){
108486
+ sqlite3DebugPrintf(pBuilder->pBest ? "ins-skip: " : "ins-noop: ");
108487
+ whereLoopPrint(pTemplate, pWInfo->pTabList);
108488
+ }
108489
+#endif
108490
+ return SQLITE_OK;
108491
+}
108492
+
108493
+/*
108494
+** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
108495
+** Try to match one more.
108496
+**
108497
+** If pProbe->tnum==0, that means pIndex is a fake index used for the
108498
+** INTEGER PRIMARY KEY.
108499
+*/
108500
+static int whereLoopAddBtreeIndex(
108501
+ WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
108502
+ struct SrcList_item *pSrc, /* FROM clause term being analyzed */
108503
+ Index *pProbe, /* An index on pSrc */
108504
+ WhereCost nInMul /* log(Number of iterations due to IN) */
108505
+){
108506
+ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
108507
+ Parse *pParse = pWInfo->pParse; /* Parsing context */
108508
+ sqlite3 *db = pParse->db; /* Database connection malloc context */
108509
+ WhereLoop *pNew; /* Template WhereLoop under construction */
108510
+ WhereTerm *pTerm; /* A WhereTerm under consideration */
108511
+ int opMask; /* Valid operators for constraints */
108512
+ WhereScan scan; /* Iterator for WHERE terms */
108513
+ Bitmask saved_prereq; /* Original value of pNew->prereq */
108514
+ u16 saved_nLTerm; /* Original value of pNew->nLTerm */
108515
+ int saved_nEq; /* Original value of pNew->u.btree.nEq */
108516
+ u32 saved_wsFlags; /* Original value of pNew->wsFlags */
108517
+ WhereCost saved_nOut; /* Original value of pNew->nOut */
108518
+ int iCol; /* Index of the column in the table */
108519
+ int rc = SQLITE_OK; /* Return code */
108520
+ WhereCost nRowEst; /* Estimated index selectivity */
108521
+ WhereCost rLogSize; /* Logarithm of table size */
108522
+ WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
108523
+
108524
+ pNew = pBuilder->pNew;
108525
+ if( db->mallocFailed ) return SQLITE_NOMEM;
108526
+
108527
+ assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
108528
+ assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
108529
+ if( pNew->wsFlags & WHERE_BTM_LIMIT ){
108530
+ opMask = WO_LT|WO_LE;
108531
+ }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
108532
+ opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
108533
+ }else{
108534
+ opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
108535
+ }
108536
+ if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
108537
+
108538
+ assert( pNew->u.btree.nEq<=pProbe->nColumn );
108539
+ if( pNew->u.btree.nEq < pProbe->nColumn ){
108540
+ iCol = pProbe->aiColumn[pNew->u.btree.nEq];
108541
+ nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
108542
+ if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
108543
+ }else{
108544
+ iCol = -1;
108545
+ nRowEst = 0;
108546
+ }
108547
+ pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
108548
+ opMask, pProbe);
108549
+ saved_nEq = pNew->u.btree.nEq;
108550
+ saved_nLTerm = pNew->nLTerm;
108551
+ saved_wsFlags = pNew->wsFlags;
108552
+ saved_prereq = pNew->prereq;
108553
+ saved_nOut = pNew->nOut;
108554
+ pNew->rSetup = 0;
108555
+ rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
108556
+ for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
108557
+ int nIn = 0;
108558
+ if( pTerm->prereqRight & pNew->maskSelf ) continue;
108559
+ pNew->wsFlags = saved_wsFlags;
108560
+ pNew->u.btree.nEq = saved_nEq;
108561
+ pNew->nLTerm = saved_nLTerm;
108562
+ if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
108563
+ pNew->aLTerm[pNew->nLTerm++] = pTerm;
108564
+ pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
108565
+ pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
108566
+ if( pTerm->eOperator & WO_IN ){
108567
+ Expr *pExpr = pTerm->pExpr;
108568
+ pNew->wsFlags |= WHERE_COLUMN_IN;
108569
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
108570
+ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
108571
+ nIn = 46; assert( 46==whereCost(25) );
108572
+ }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
108573
+ /* "x IN (value, value, ...)" */
108574
+ nIn = whereCost(pExpr->x.pList->nExpr);
108575
+ }
108576
+ pNew->rRun += nIn;
108577
+ pNew->u.btree.nEq++;
108578
+ pNew->nOut = nRowEst + nInMul + nIn;
108579
+ }else if( pTerm->eOperator & (WO_EQ) ){
108580
+ assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
108581
+ || nInMul==0 );
108582
+ pNew->wsFlags |= WHERE_COLUMN_EQ;
108583
+ if( iCol<0
108584
+ || (pProbe->onError!=OE_None && nInMul==0
108585
+ && pNew->u.btree.nEq==pProbe->nColumn-1)
108586
+ ){
108587
+ assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
108588
+ pNew->wsFlags |= WHERE_ONEROW;
108589
+ }
108590
+ pNew->u.btree.nEq++;
108591
+ pNew->nOut = nRowEst + nInMul;
108592
+ }else if( pTerm->eOperator & (WO_ISNULL) ){
108593
+ pNew->wsFlags |= WHERE_COLUMN_NULL;
108594
+ pNew->u.btree.nEq++;
108595
+ /* TUNING: IS NULL selects 2 rows */
108596
+ nIn = 10; assert( 10==whereCost(2) );
108597
+ pNew->nOut = nRowEst + nInMul + nIn;
108598
+ }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
108599
+ testcase( pTerm->eOperator & WO_GT );
108600
+ testcase( pTerm->eOperator & WO_GE );
108601
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
108602
+ pBtm = pTerm;
108603
+ pTop = 0;
108604
+ }else{
108605
+ assert( pTerm->eOperator & (WO_LT|WO_LE) );
108606
+ testcase( pTerm->eOperator & WO_LT );
108607
+ testcase( pTerm->eOperator & WO_LE );
108608
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
108609
+ pTop = pTerm;
108610
+ pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
108611
+ pNew->aLTerm[pNew->nLTerm-2] : 0;
108612
+ }
108613
+ if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
108614
+ /* Adjust nOut and rRun for STAT3 range values */
108615
+ WhereCost rDiv;
108616
+ whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
108617
+ pBtm, pTop, &rDiv);
108618
+ pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
108619
+ }
108620
+#ifdef SQLITE_ENABLE_STAT3
108621
+ if( pNew->u.btree.nEq==1 && pProbe->nSample ){
108622
+ tRowcnt nOut = 0;
108623
+ if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
108624
+ testcase( pTerm->eOperator & WO_EQ );
108625
+ testcase( pTerm->eOperator & WO_ISNULL );
108626
+ rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
108627
+ }else if( (pTerm->eOperator & WO_IN)
108628
+ && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
108629
+ rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
108630
+ }
108631
+ if( rc==SQLITE_OK ) pNew->nOut = whereCost(nOut);
108632
+ }
108633
+#endif
108634
+ if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
108635
+ /* Each row involves a step of the index, then a binary search of
108636
+ ** the main table */
108637
+ pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
108638
+ }
108639
+ /* Step cost for each output row */
108640
+ pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
108641
+ /* TBD: Adjust nOut for additional constraints */
108642
+ rc = whereLoopInsert(pBuilder, pNew);
108643
+ if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
108644
+ && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
108645
+ ){
108646
+ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
108647
+ }
108648
+ }
108649
+ pNew->prereq = saved_prereq;
108650
+ pNew->u.btree.nEq = saved_nEq;
108651
+ pNew->wsFlags = saved_wsFlags;
108652
+ pNew->nOut = saved_nOut;
108653
+ pNew->nLTerm = saved_nLTerm;
108654
+ return rc;
108655
+}
108656
+
108657
+/*
108658
+** Return True if it is possible that pIndex might be useful in
108659
+** implementing the ORDER BY clause in pBuilder.
108660
+**
108661
+** Return False if pBuilder does not contain an ORDER BY clause or
108662
+** if there is no way for pIndex to be useful in implementing that
108663
+** ORDER BY clause.
108664
+*/
108665
+static int indexMightHelpWithOrderBy(
108666
+ WhereLoopBuilder *pBuilder,
108667
+ Index *pIndex,
108668
+ int iCursor
108669
+){
108670
+ ExprList *pOB;
108671
+ int ii, jj;
108672
+
108673
+ if( pIndex->bUnordered ) return 0;
108674
+ if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
108675
+ for(ii=0; ii<pOB->nExpr; ii++){
108676
+ Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
108677
+ if( pExpr->op!=TK_COLUMN ) return 0;
108678
+ if( pExpr->iTable==iCursor ){
108679
+ for(jj=0; jj<pIndex->nColumn; jj++){
108680
+ if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
108681
+ }
108682
+ }
108683
+ }
108684
+ return 0;
108685
+}
108686
+
108687
+/*
108688
+** Return a bitmask where 1s indicate that the corresponding column of
108689
+** the table is used by an index. Only the first 63 columns are considered.
108690
+*/
108691
+static Bitmask columnsInIndex(Index *pIdx){
108692
+ Bitmask m = 0;
108693
+ int j;
108694
+ for(j=pIdx->nColumn-1; j>=0; j--){
108695
+ int x = pIdx->aiColumn[j];
108696
+ testcase( x==BMS-1 );
108697
+ testcase( x==BMS-2 );
108698
+ if( x<BMS-1 ) m |= MASKBIT(x);
108699
+ }
108700
+ return m;
108701
+}
108702
+
108703
+
108704
+/*
108705
+** Add all WhereLoop objects a single table of the join were the table
108706
+** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
108707
+** a b-tree table, not a virtual table.
108708
+*/
108709
+static int whereLoopAddBtree(
108710
+ WhereLoopBuilder *pBuilder, /* WHERE clause information */
108711
+ Bitmask mExtra /* Extra prerequesites for using this table */
108712
+){
108713
+ WhereInfo *pWInfo; /* WHERE analysis context */
108714
+ Index *pProbe; /* An index we are evaluating */
108715
+ Index sPk; /* A fake index object for the primary key */
108716
+ tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
108717
+ int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
108718
+ SrcList *pTabList; /* The FROM clause */
108719
+ struct SrcList_item *pSrc; /* The FROM clause btree term to add */
108720
+ WhereLoop *pNew; /* Template WhereLoop object */
108721
+ int rc = SQLITE_OK; /* Return code */
108722
+ int iSortIdx = 1; /* Index number */
108723
+ int b; /* A boolean value */
108724
+ WhereCost rSize; /* number of rows in the table */
108725
+ WhereCost rLogSize; /* Logarithm of the number of rows in the table */
108726
+
108727
+ pNew = pBuilder->pNew;
108728
+ pWInfo = pBuilder->pWInfo;
108729
+ pTabList = pWInfo->pTabList;
108730
+ pSrc = pTabList->a + pNew->iTab;
108731
+ assert( !IsVirtual(pSrc->pTab) );
108732
+
108733
+ if( pSrc->pIndex ){
108734
+ /* An INDEXED BY clause specifies a particular index to use */
108735
+ pProbe = pSrc->pIndex;
108736
+ }else{
108737
+ /* There is no INDEXED BY clause. Create a fake Index object in local
108738
+ ** variable sPk to represent the rowid primary key index. Make this
108739
+ ** fake index the first in a chain of Index objects with all of the real
108740
+ ** indices to follow */
108741
+ Index *pFirst; /* First of real indices on the table */
108742
+ memset(&sPk, 0, sizeof(Index));
108743
+ sPk.nColumn = 1;
108744
+ sPk.aiColumn = &aiColumnPk;
108745
+ sPk.aiRowEst = aiRowEstPk;
108746
+ sPk.onError = OE_Replace;
108747
+ sPk.pTable = pSrc->pTab;
108748
+ aiRowEstPk[0] = pSrc->pTab->nRowEst;
108749
+ aiRowEstPk[1] = 1;
108750
+ pFirst = pSrc->pTab->pIndex;
108751
+ if( pSrc->notIndexed==0 ){
108752
+ /* The real indices of the table are only considered if the
108753
+ ** NOT INDEXED qualifier is omitted from the FROM clause */
108754
+ sPk.pNext = pFirst;
108755
+ }
108756
+ pProbe = &sPk;
108757
+ }
108758
+ rSize = whereCost(pSrc->pTab->nRowEst);
108759
+ rLogSize = estLog(rSize);
108760
+
108761
+ /* Automatic indexes */
108762
+ if( !pBuilder->pBest
108763
+ && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
108764
+ && pSrc->pIndex==0
108765
+ && !pSrc->viaCoroutine
108766
+ && !pSrc->notIndexed
108767
+ && !pSrc->isCorrelated
108768
+ ){
108769
+ /* Generate auto-index WhereLoops */
108770
+ WhereClause *pWC = pBuilder->pWC;
108771
+ WhereTerm *pTerm;
108772
+ WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
108773
+ for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
108774
+ if( pTerm->prereqRight & pNew->maskSelf ) continue;
108775
+ if( termCanDriveIndex(pTerm, pSrc, 0) ){
108776
+ pNew->u.btree.nEq = 1;
108777
+ pNew->u.btree.pIndex = 0;
108778
+ pNew->nLTerm = 1;
108779
+ pNew->aLTerm[0] = pTerm;
108780
+ /* TUNING: One-time cost for computing the automatic index is
108781
+ ** approximately 6*N*log2(N) where N is the number of rows in
108782
+ ** the table being indexed. */
108783
+ pNew->rSetup = rLogSize + rSize + 26; assert( 26==whereCost(6) );
108784
+ /* TUNING: Each index lookup yields 10 rows in the table */
108785
+ pNew->nOut = 33; assert( 33==whereCost(10) );
108786
+ pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
108787
+ pNew->wsFlags = WHERE_TEMP_INDEX;
108788
+ pNew->prereq = mExtra | pTerm->prereqRight;
108789
+ rc = whereLoopInsert(pBuilder, pNew);
108790
+ }
108791
+ }
108792
+ }
108793
+
108794
+ /* Loop over all indices
108795
+ */
108796
+ for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
108797
+ pNew->u.btree.nEq = 0;
108798
+ pNew->nLTerm = 0;
108799
+ pNew->iSortIdx = 0;
108800
+ pNew->rSetup = 0;
108801
+ pNew->prereq = mExtra;
108802
+ pNew->nOut = rSize;
108803
+ pNew->u.btree.pIndex = pProbe;
108804
+ b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
108805
+ /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
108806
+ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
108807
+ if( pProbe->tnum<=0 ){
108808
+ /* Integer primary key index */
108809
+ pNew->wsFlags = WHERE_IPK;
108810
+
108811
+ /* Full table scan */
108812
+ pNew->iSortIdx = b ? iSortIdx : 0;
108813
+ /* TUNING: Cost of full table scan is 3*(N + log2(N)).
108814
+ ** + The extra 3 factor is to encourage the use of indexed lookups
108815
+ ** over full scans. A smaller constant 2 is used for covering
108816
+ ** index scans so that a covering index scan will be favored over
108817
+ ** a table scan. */
108818
+ pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
108819
+ rc = whereLoopInsert(pBuilder, pNew);
108820
+ if( rc ) break;
108821
+ }else{
108822
+ Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
108823
+ pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
108824
+
108825
+ /* Full scan via index */
108826
+ if( b
108827
+ || ( m==0
108828
+ && pProbe->bUnordered==0
108829
+ && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
108830
+ && sqlite3GlobalConfig.bUseCis
108831
+ && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
108832
+ )
108833
+ ){
108834
+ pNew->iSortIdx = b ? iSortIdx : 0;
108835
+ if( m==0 ){
108836
+ /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
108837
+ ** + The extra 2 factor is to encourage the use of indexed lookups
108838
+ ** over index scans. A table scan uses a factor of 3 so that
108839
+ ** index scans are favored over table scans.
108840
+ ** + If this covering index might also help satisfy the ORDER BY
108841
+ ** clause, then the cost is fudged down slightly so that this
108842
+ ** index is favored above other indices that have no hope of
108843
+ ** helping with the ORDER BY. */
108844
+ pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
108845
+ }else{
108846
+ assert( b!=0 );
108847
+ /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
108848
+ ** which we will simplify to just N*log2(N) */
108849
+ pNew->rRun = rSize + rLogSize;
108850
+ }
108851
+ rc = whereLoopInsert(pBuilder, pNew);
108852
+ if( rc ) break;
108853
+ }
108854
+ }
108855
+ rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
108856
+
108857
+ /* If there was an INDEXED BY clause, then only that one index is
108858
+ ** considered. */
108859
+ if( pSrc->pIndex ) break;
108860
+ }
108861
+ return rc;
108862
+}
108863
+
108864
+#ifndef SQLITE_OMIT_VIRTUALTABLE
108865
+/*
108866
+** Add all WhereLoop objects for a table of the join identified by
108867
+** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
108868
+*/
108869
+static int whereLoopAddVirtual(
108870
+ WhereLoopBuilder *pBuilder /* WHERE clause information */
108871
+){
108872
+ WhereInfo *pWInfo; /* WHERE analysis context */
108873
+ Parse *pParse; /* The parsing context */
108874
+ WhereClause *pWC; /* The WHERE clause */
108875
+ struct SrcList_item *pSrc; /* The FROM clause term to search */
108876
+ Table *pTab;
108877
+ sqlite3 *db;
108878
+ sqlite3_index_info *pIdxInfo;
108879
+ struct sqlite3_index_constraint *pIdxCons;
108880
+ struct sqlite3_index_constraint_usage *pUsage;
108881
+ WhereTerm *pTerm;
108882
+ int i, j;
108883
+ int iTerm, mxTerm;
108884
+ int nConstraint;
108885
+ int seenIn = 0; /* True if an IN operator is seen */
108886
+ int seenVar = 0; /* True if a non-constant constraint is seen */
108887
+ int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
108888
+ WhereLoop *pNew;
108889
+ int rc = SQLITE_OK;
108890
+
108891
+ pWInfo = pBuilder->pWInfo;
108892
+ pParse = pWInfo->pParse;
108893
+ db = pParse->db;
108894
+ pWC = pBuilder->pWC;
108895
+ pNew = pBuilder->pNew;
108896
+ pSrc = &pWInfo->pTabList->a[pNew->iTab];
108897
+ pTab = pSrc->pTab;
108898
+ assert( IsVirtual(pTab) );
108899
+ pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
108900
+ if( pIdxInfo==0 ) return SQLITE_NOMEM;
108901
+ pNew->prereq = 0;
108902
+ pNew->rSetup = 0;
108903
+ pNew->wsFlags = WHERE_VIRTUALTABLE;
108904
+ pNew->nLTerm = 0;
108905
+ pNew->u.vtab.needFree = 0;
108906
+ pUsage = pIdxInfo->aConstraintUsage;
108907
+ nConstraint = pIdxInfo->nConstraint;
108908
+ if( whereLoopResize(db, pNew, nConstraint) ){
108909
+ sqlite3DbFree(db, pIdxInfo);
108910
+ return SQLITE_NOMEM;
108911
+ }
108912
+
108913
+ for(iPhase=0; iPhase<=3; iPhase++){
108914
+ if( !seenIn && (iPhase&1)!=0 ){
108915
+ iPhase++;
108916
+ if( iPhase>3 ) break;
108917
+ }
108918
+ if( !seenVar && iPhase>1 ) break;
108919
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108920
+ for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
108921
+ j = pIdxCons->iTermOffset;
108922
+ pTerm = &pWC->a[j];
108923
+ switch( iPhase ){
108924
+ case 0: /* Constants without IN operator */
108925
+ pIdxCons->usable = 0;
108926
+ if( (pTerm->eOperator & WO_IN)!=0 ){
108927
+ seenIn = 1;
108928
+ }
108929
+ if( pTerm->prereqRight!=0 ){
108930
+ seenVar = 1;
108931
+ }else if( (pTerm->eOperator & WO_IN)==0 ){
108932
+ pIdxCons->usable = 1;
108933
+ }
108934
+ break;
108935
+ case 1: /* Constants with IN operators */
108936
+ assert( seenIn );
108937
+ pIdxCons->usable = (pTerm->prereqRight==0);
108938
+ break;
108939
+ case 2: /* Variables without IN */
108940
+ assert( seenVar );
108941
+ pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
108942
+ break;
108943
+ default: /* Variables with IN */
108944
+ assert( seenVar && seenIn );
108945
+ pIdxCons->usable = 1;
108946
+ break;
108947
+ }
108948
+ }
108949
+ memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
108950
+ if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
108951
+ pIdxInfo->idxStr = 0;
108952
+ pIdxInfo->idxNum = 0;
108953
+ pIdxInfo->needToFreeIdxStr = 0;
108954
+ pIdxInfo->orderByConsumed = 0;
108955
+ pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
108956
+ rc = vtabBestIndex(pParse, pTab, pIdxInfo);
108957
+ if( rc ) goto whereLoopAddVtab_exit;
108958
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108959
+ pNew->prereq = 0;
108960
+ mxTerm = -1;
108961
+ assert( pNew->nLSlot>=nConstraint );
108962
+ for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
108963
+ pNew->u.vtab.omitMask = 0;
108964
+ for(i=0; i<nConstraint; i++, pIdxCons++){
108965
+ if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
108966
+ j = pIdxCons->iTermOffset;
108967
+ if( iTerm>=nConstraint
108968
+ || j<0
108969
+ || j>=pWC->nTerm
108970
+ || pNew->aLTerm[iTerm]!=0
108971
+ ){
108972
+ rc = SQLITE_ERROR;
108973
+ sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
108974
+ goto whereLoopAddVtab_exit;
108975
+ }
108976
+ testcase( iTerm==nConstraint-1 );
108977
+ testcase( j==0 );
108978
+ testcase( j==pWC->nTerm-1 );
108979
+ pTerm = &pWC->a[j];
108980
+ pNew->prereq |= pTerm->prereqRight;
108981
+ assert( iTerm<pNew->nLSlot );
108982
+ pNew->aLTerm[iTerm] = pTerm;
108983
+ if( iTerm>mxTerm ) mxTerm = iTerm;
108984
+ testcase( iTerm==15 );
108985
+ testcase( iTerm==16 );
108986
+ if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
108987
+ if( (pTerm->eOperator & WO_IN)!=0 ){
108988
+ if( pUsage[i].omit==0 ){
108989
+ /* Do not attempt to use an IN constraint if the virtual table
108990
+ ** says that the equivalent EQ constraint cannot be safely omitted.
108991
+ ** If we do attempt to use such a constraint, some rows might be
108992
+ ** repeated in the output. */
108993
+ break;
108994
+ }
108995
+ /* A virtual table that is constrained by an IN clause may not
108996
+ ** consume the ORDER BY clause because (1) the order of IN terms
108997
+ ** is not necessarily related to the order of output terms and
108998
+ ** (2) Multiple outputs from a single IN value will not merge
108999
+ ** together. */
109000
+ pIdxInfo->orderByConsumed = 0;
109001
+ }
109002
+ }
109003
+ }
109004
+ if( i>=nConstraint ){
109005
+ pNew->nLTerm = mxTerm+1;
109006
+ assert( pNew->nLTerm<=pNew->nLSlot );
109007
+ pNew->u.vtab.idxNum = pIdxInfo->idxNum;
109008
+ pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
109009
+ pIdxInfo->needToFreeIdxStr = 0;
109010
+ pNew->u.vtab.idxStr = pIdxInfo->idxStr;
109011
+ pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
109012
+ && pIdxInfo->orderByConsumed);
109013
+ pNew->rSetup = 0;
109014
+ pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
109015
+ /* TUNING: Every virtual table query returns 25 rows */
109016
+ pNew->nOut = 46; assert( 46==whereCost(25) );
109017
+ whereLoopInsert(pBuilder, pNew);
109018
+ if( pNew->u.vtab.needFree ){
109019
+ sqlite3_free(pNew->u.vtab.idxStr);
109020
+ pNew->u.vtab.needFree = 0;
109021
+ }
109022
+ }
109023
+ }
109024
+
109025
+whereLoopAddVtab_exit:
109026
+ if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
109027
+ sqlite3DbFree(db, pIdxInfo);
109028
+ return rc;
109029
+}
109030
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
109031
+
109032
+/*
109033
+** Add WhereLoop entries to handle OR terms. This works for either
109034
+** btrees or virtual tables.
109035
+*/
109036
+static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
109037
+ WhereInfo *pWInfo = pBuilder->pWInfo;
109038
+ WhereClause *pWC;
109039
+ WhereLoop *pNew;
109040
+ WhereTerm *pTerm, *pWCEnd;
109041
+ int rc = SQLITE_OK;
109042
+ int iCur;
109043
+ WhereClause tempWC;
109044
+ WhereLoopBuilder sSubBuild;
109045
+ WhereLoop sBest;
109046
+ struct SrcList_item *pItem;
109047
+
109048
+ pWC = pBuilder->pWC;
109049
+ if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
109050
+ pWCEnd = pWC->a + pWC->nTerm;
109051
+ pNew = pBuilder->pNew;
109052
+
109053
+ for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
109054
+ if( (pTerm->eOperator & WO_OR)!=0
109055
+ && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
109056
+ ){
109057
+ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
109058
+ WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
109059
+ WhereTerm *pOrTerm;
109060
+ WhereCost rTotal = 0;
109061
+ WhereCost nRow = 0;
109062
+ Bitmask prereq = mExtra;
109063
+
109064
+ whereLoopInit(&sBest);
109065
+ pItem = pWInfo->pTabList->a + pNew->iTab;
109066
+ iCur = pItem->iCursor;
109067
+ sSubBuild = *pBuilder;
109068
+ sSubBuild.pOrderBy = 0;
109069
+ sSubBuild.pBest = &sBest;
109070
+
109071
+ for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
109072
+ if( (pOrTerm->eOperator & WO_AND)!=0 ){
109073
+ sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
109074
+ }else if( pOrTerm->leftCursor==iCur ){
109075
+ tempWC.pWInfo = pWC->pWInfo;
109076
+ tempWC.pOuter = pWC;
109077
+ tempWC.op = TK_AND;
109078
+ tempWC.nTerm = 1;
109079
+ tempWC.a = pOrTerm;
109080
+ sSubBuild.pWC = &tempWC;
109081
+ }else{
109082
+ continue;
109083
+ }
109084
+ sBest.maskSelf = 0;
109085
+ sBest.rSetup = 0;
109086
+ sBest.rRun = 0;
109087
+#ifndef SQLITE_OMIT_VIRTUALTABLE
109088
+ if( IsVirtual(pItem->pTab) ){
109089
+ rc = whereLoopAddVirtual(&sSubBuild);
109090
+ }else
109091
+#endif
109092
+ {
109093
+ rc = whereLoopAddBtree(&sSubBuild, mExtra);
109094
+ }
109095
+ /* sBest.maskSelf is always zero if an error occurs */
109096
+ assert( rc==SQLITE_OK || sBest.maskSelf==0 );
109097
+ if( sBest.maskSelf==0 ) break;
109098
+ assert( sBest.rSetup==0 );
109099
+ rTotal = whereCostAdd(rTotal, sBest.rRun);
109100
+ nRow = whereCostAdd(nRow, sBest.nOut);
109101
+ prereq |= sBest.prereq;
109102
+ }
109103
+ assert( pNew->nLSlot>=1 );
109104
+ if( sBest.maskSelf ){
109105
+ pNew->nLTerm = 1;
109106
+ pNew->aLTerm[0] = pTerm;
109107
+ pNew->wsFlags = WHERE_MULTI_OR;
109108
+ pNew->rSetup = 0;
109109
+ /* TUNING: Multiple by 3.5 for the secondary table lookup */
109110
+ pNew->rRun = rTotal + 18; assert( 18==whereCost(7)-whereCost(2) );
109111
+ pNew->nOut = nRow;
109112
+ pNew->prereq = prereq;
109113
+ memset(&pNew->u, 0, sizeof(pNew->u));
109114
+ rc = whereLoopInsert(pBuilder, pNew);
109115
+ }
109116
+ whereLoopClear(pWInfo->pParse->db, &sBest);
109117
+ }
109118
+ }
109119
+ return rc;
109120
+}
109121
+
109122
+/*
109123
+** Add all WhereLoop objects for all tables
109124
+*/
109125
+static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
109126
+ WhereInfo *pWInfo = pBuilder->pWInfo;
109127
+ Bitmask mExtra = 0;
109128
+ Bitmask mPrior = 0;
109129
+ int iTab;
109130
+ SrcList *pTabList = pWInfo->pTabList;
109131
+ struct SrcList_item *pItem;
109132
+ sqlite3 *db = pWInfo->pParse->db;
109133
+ int nTabList = pWInfo->nLevel;
109134
+ int rc = SQLITE_OK;
109135
+ u8 priorJoinType = 0;
109136
+ WhereLoop *pNew;
109137
+
109138
+ /* Loop over the tables in the join, from left to right */
109139
+ pNew = pBuilder->pNew;
109140
+ whereLoopInit(pNew);
109141
+ for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
109142
+ pNew->iTab = iTab;
109143
+ pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
109144
+ if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
109145
+ mExtra = mPrior;
109146
+ }
109147
+ priorJoinType = pItem->jointype;
109148
+ if( IsVirtual(pItem->pTab) ){
109149
+ rc = whereLoopAddVirtual(pBuilder);
109150
+ }else{
109151
+ rc = whereLoopAddBtree(pBuilder, mExtra);
109152
+ }
109153
+ if( rc==SQLITE_OK ){
109154
+ rc = whereLoopAddOr(pBuilder, mExtra);
109155
+ }
109156
+ mPrior |= pNew->maskSelf;
109157
+ if( rc || db->mallocFailed ) break;
109158
+ }
109159
+ whereLoopClear(db, pNew);
109160
+ return rc;
109161
+}
109162
+
109163
+/*
109164
+** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
109165
+** parameters) to see if it outputs rows in the requested ORDER BY
109166
+** (or GROUP BY) without requiring a separate source operation. Return:
109167
+**
109168
+** 0: ORDER BY is not satisfied. Sorting required
109169
+** 1: ORDER BY is satisfied. Omit sorting
109170
+** -1: Unknown at this time
109171
+**
109172
+*/
109173
+static int wherePathSatisfiesOrderBy(
109174
+ WhereInfo *pWInfo, /* The WHERE clause */
109175
+ ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
109176
+ WherePath *pPath, /* The WherePath to check */
109177
+ u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
109178
+ u16 nLoop, /* Number of entries in pPath->aLoop[] */
109179
+ WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
109180
+ Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
109181
+){
109182
+ u8 revSet; /* True if rev is known */
109183
+ u8 rev; /* Composite sort order */
109184
+ u8 revIdx; /* Index sort order */
109185
+ u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
109186
+ u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
109187
+ u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
109188
+ u16 nColumn; /* Number of columns in pIndex */
109189
+ u16 nOrderBy; /* Number terms in the ORDER BY clause */
109190
+ int iLoop; /* Index of WhereLoop in pPath being processed */
109191
+ int i, j; /* Loop counters */
109192
+ int iCur; /* Cursor number for current WhereLoop */
109193
+ int iColumn; /* A column number within table iCur */
109194
+ WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
109195
+ WhereTerm *pTerm; /* A single term of the WHERE clause */
109196
+ Expr *pOBExpr; /* An expression from the ORDER BY clause */
109197
+ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
109198
+ Index *pIndex; /* The index associated with pLoop */
109199
+ sqlite3 *db = pWInfo->pParse->db; /* Database connection */
109200
+ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
109201
+ Bitmask obDone; /* Mask of all ORDER BY terms */
109202
+ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
109203
+ Bitmask ready; /* Mask of inner loops */
109204
+
109205
+ /*
109206
+ ** We say the WhereLoop is "one-row" if it generates no more than one
109207
+ ** row of output. A WhereLoop is one-row if all of the following are true:
109208
+ ** (a) All index columns match with WHERE_COLUMN_EQ.
109209
+ ** (b) The index is unique
109210
+ ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
109211
+ ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
109212
+ **
109213
+ ** We say the WhereLoop is "order-distinct" if the set of columns from
109214
+ ** that WhereLoop that are in the ORDER BY clause are different for every
109215
+ ** row of the WhereLoop. Every one-row WhereLoop is automatically
109216
+ ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
109217
+ ** is not order-distinct. To be order-distinct is not quite the same as being
109218
+ ** UNIQUE since a UNIQUE column or index can have multiple rows that
109219
+ ** are NULL and NULL values are equivalent for the purpose of order-distinct.
109220
+ ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
109221
+ **
109222
+ ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
109223
+ ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
109224
+ ** automatically order-distinct.
109225
+ */
109226
+
109227
+ assert( pOrderBy!=0 );
109228
+
109229
+ /* Sortability of virtual tables is determined by the xBestIndex method
109230
+ ** of the virtual table itself */
109231
+ if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
109232
+ testcase( nLoop>0 ); /* True when outer loops are one-row and match
109233
+ ** no ORDER BY terms */
109234
+ return pLast->u.vtab.isOrdered;
109235
+ }
109236
+ if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
109237
+
109238
+ nOrderBy = pOrderBy->nExpr;
109239
+ testcase( nOrderBy==BMS-1 );
109240
+ if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
109241
+ isOrderDistinct = 1;
109242
+ obDone = MASKBIT(nOrderBy)-1;
109243
+ orderDistinctMask = 0;
109244
+ ready = 0;
109245
+ for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
109246
+ if( iLoop>0 ) ready |= pLoop->maskSelf;
109247
+ pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
109248
+ assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
109249
+ iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
109250
+
109251
+ /* Mark off any ORDER BY term X that is a column in the table of
109252
+ ** the current loop for which there is term in the WHERE
109253
+ ** clause of the form X IS NULL or X=? that reference only outer
109254
+ ** loops.
109255
+ */
109256
+ for(i=0; i<nOrderBy; i++){
109257
+ if( MASKBIT(i) & obSat ) continue;
109258
+ pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109259
+ if( pOBExpr->op!=TK_COLUMN ) continue;
109260
+ if( pOBExpr->iTable!=iCur ) continue;
109261
+ pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
109262
+ ~ready, WO_EQ|WO_ISNULL, 0);
109263
+ if( pTerm==0 ) continue;
109264
+ if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
109265
+ const char *z1, *z2;
109266
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109267
+ if( !pColl ) pColl = db->pDfltColl;
109268
+ z1 = pColl->zName;
109269
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
109270
+ if( !pColl ) pColl = db->pDfltColl;
109271
+ z2 = pColl->zName;
109272
+ if( sqlite3StrICmp(z1, z2)!=0 ) continue;
109273
+ }
109274
+ obSat |= MASKBIT(i);
109275
+ }
109276
+
109277
+ if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
109278
+ if( pLoop->wsFlags & WHERE_IPK ){
109279
+ pIndex = 0;
109280
+ nColumn = 0;
109281
+ }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
109282
+ return 0;
109283
+ }else{
109284
+ nColumn = pIndex->nColumn;
109285
+ isOrderDistinct = pIndex->onError!=OE_None;
109286
+ }
109287
+
109288
+ /* Loop through all columns of the index and deal with the ones
109289
+ ** that are not constrained by == or IN.
109290
+ */
109291
+ rev = revSet = 0;
109292
+ distinctColumns = 0;
109293
+ for(j=0; j<=nColumn; j++){
109294
+ u8 bOnce; /* True to run the ORDER BY search loop */
109295
+
109296
+ /* Skip over == and IS NULL terms */
109297
+ if( j<pLoop->u.btree.nEq
109298
+ && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
109299
+ ){
109300
+ if( i & WO_ISNULL ){
109301
+ testcase( isOrderDistinct );
109302
+ isOrderDistinct = 0;
109303
+ }
109304
+ continue;
109305
+ }
109306
+
109307
+ /* Get the column number in the table (iColumn) and sort order
109308
+ ** (revIdx) for the j-th column of the index.
109309
+ */
109310
+ if( j<nColumn ){
109311
+ /* Normal index columns */
109312
+ iColumn = pIndex->aiColumn[j];
109313
+ revIdx = pIndex->aSortOrder[j];
109314
+ if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
109315
+ }else{
109316
+ /* The ROWID column at the end */
109317
+ assert( j==nColumn );
109318
+ iColumn = -1;
109319
+ revIdx = 0;
109320
+ }
109321
+
109322
+ /* An unconstrained column that might be NULL means that this
109323
+ ** WhereLoop is not well-ordered
109324
+ */
109325
+ if( isOrderDistinct
109326
+ && iColumn>=0
109327
+ && j>=pLoop->u.btree.nEq
109328
+ && pIndex->pTable->aCol[iColumn].notNull==0
109329
+ ){
109330
+ isOrderDistinct = 0;
109331
+ }
109332
+
109333
+ /* Find the ORDER BY term that corresponds to the j-th column
109334
+ ** of the index and and mark that ORDER BY term off
109335
+ */
109336
+ bOnce = 1;
109337
+ isMatch = 0;
109338
+ for(i=0; bOnce && i<nOrderBy; i++){
109339
+ if( MASKBIT(i) & obSat ) continue;
109340
+ pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109341
+ testcase( wctrlFlags & WHERE_GROUPBY );
109342
+ testcase( wctrlFlags & WHERE_DISTINCTBY );
109343
+ if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
109344
+ if( pOBExpr->op!=TK_COLUMN ) continue;
109345
+ if( pOBExpr->iTable!=iCur ) continue;
109346
+ if( pOBExpr->iColumn!=iColumn ) continue;
109347
+ if( iColumn>=0 ){
109348
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109349
+ if( !pColl ) pColl = db->pDfltColl;
109350
+ if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
109351
+ }
109352
+ isMatch = 1;
109353
+ break;
109354
+ }
109355
+ if( isMatch ){
109356
+ if( iColumn<0 ){
109357
+ testcase( distinctColumns==0 );
109358
+ distinctColumns = 1;
109359
+ }
109360
+ obSat |= MASKBIT(i);
109361
+ if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
109362
+ /* Make sure the sort order is compatible in an ORDER BY clause.
109363
+ ** Sort order is irrelevant for a GROUP BY clause. */
109364
+ if( revSet ){
109365
+ if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
109366
+ }else{
109367
+ rev = revIdx ^ pOrderBy->a[i].sortOrder;
109368
+ if( rev ) *pRevMask |= MASKBIT(iLoop);
109369
+ revSet = 1;
109370
+ }
109371
+ }
109372
+ }else{
109373
+ /* No match found */
109374
+ if( j==0 || j<nColumn ){
109375
+ testcase( isOrderDistinct!=0 );
109376
+ isOrderDistinct = 0;
109377
+ }
109378
+ break;
109379
+ }
109380
+ } /* end Loop over all index columns */
109381
+ if( distinctColumns ){
109382
+ testcase( isOrderDistinct==0 );
109383
+ isOrderDistinct = 1;
109384
+ }
109385
+ } /* end-if not one-row */
109386
+
109387
+ /* Mark off any other ORDER BY terms that reference pLoop */
109388
+ if( isOrderDistinct ){
109389
+ orderDistinctMask |= pLoop->maskSelf;
109390
+ for(i=0; i<nOrderBy; i++){
109391
+ Expr *p;
109392
+ if( MASKBIT(i) & obSat ) continue;
109393
+ p = pOrderBy->a[i].pExpr;
109394
+ if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
109395
+ obSat |= MASKBIT(i);
109396
+ }
109397
+ }
109398
+ }
109399
+ } /* End the loop over all WhereLoops from outer-most down to inner-most */
109400
+ if( obSat==obDone ) return 1;
109401
+ if( !isOrderDistinct ) return 0;
109402
+ return -1;
109403
+}
109404
+
109405
+#ifdef WHERETRACE_ENABLED
109406
+/* For debugging use only: */
109407
+static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
109408
+ static char zName[65];
109409
+ int i;
109410
+ for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
109411
+ if( pLast ) zName[i++] = pLast->cId;
109412
+ zName[i] = 0;
109413
+ return zName;
109414
+}
109415
+#endif
109416
+
109417
+
109418
+/*
109419
+** Given the list of WhereLoop objects on pWInfo->pLoops, this routine
109420
+** attempts to find the lowest cost path that visits each WhereLoop
109421
+** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
109422
+**
109423
+** Assume that the total number of output rows that will need to be sorted
109424
+** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
109425
+** costs if nRowEst==0.
109426
+**
109427
+** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
109428
+** error occurs.
109429
+*/
109430
+static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
109431
+ int mxChoice; /* Maximum number of simultaneous paths tracked */
109432
+ int nLoop; /* Number of terms in the join */
109433
+ Parse *pParse; /* Parsing context */
109434
+ sqlite3 *db; /* The database connection */
109435
+ int iLoop; /* Loop counter over the terms of the join */
109436
+ int ii, jj; /* Loop counters */
109437
+ WhereCost rCost; /* Cost of a path */
109438
+ WhereCost mxCost = 0; /* Maximum cost of a set of paths */
109439
+ WhereCost rSortCost; /* Cost to do a sort */
109440
+ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
109441
+ WherePath *aFrom; /* All nFrom paths at the previous level */
109442
+ WherePath *aTo; /* The nTo best paths at the current level */
109443
+ WherePath *pFrom; /* An element of aFrom[] that we are working on */
109444
+ WherePath *pTo; /* An element of aTo[] that we are working on */
109445
+ WhereLoop *pWLoop; /* One of the WhereLoop objects */
109446
+ WhereLoop **pX; /* Used to divy up the pSpace memory */
109447
+ char *pSpace; /* Temporary memory used by this routine */
109448
+
109449
+ pParse = pWInfo->pParse;
109450
+ db = pParse->db;
109451
+ nLoop = pWInfo->nLevel;
109452
+ /* TUNING: For simple queries, only the best path is tracked.
109453
+ ** For 2-way joins, the 5 best paths are followed.
109454
+ ** For joins of 3 or more tables, track the 10 best paths */
109455
+ mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
109456
+ assert( nLoop<=pWInfo->pTabList->nSrc );
109457
+ WHERETRACE(0x002, ("---- begin solver\n"));
109458
+
109459
+ /* Allocate and initialize space for aTo and aFrom */
109460
+ ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
109461
+ pSpace = sqlite3DbMallocRaw(db, ii);
109462
+ if( pSpace==0 ) return SQLITE_NOMEM;
109463
+ aTo = (WherePath*)pSpace;
109464
+ aFrom = aTo+mxChoice;
109465
+ memset(aFrom, 0, sizeof(aFrom[0]));
109466
+ pX = (WhereLoop**)(aFrom+mxChoice);
109467
+ for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
109468
+ pFrom->aLoop = pX;
109469
+ }
109470
+
109471
+ /* Seed the search with a single WherePath containing zero WhereLoops.
109472
+ **
109473
+ ** TUNING: Do not let the number of iterations go above 25. If the cost
109474
+ ** of computing an automatic index is not paid back within the first 25
109475
+ ** rows, then do not use the automatic index. */
109476
+ aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
109477
+ nFrom = 1;
109478
+
109479
+ /* Precompute the cost of sorting the final result set, if the caller
109480
+ ** to sqlite3WhereBegin() was concerned about sorting */
109481
+ rSortCost = 0;
109482
+ if( pWInfo->pOrderBy==0 || nRowEst==0 ){
109483
+ aFrom[0].isOrderedValid = 1;
109484
+ }else{
109485
+ /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
109486
+ ** number of output rows. */
109487
+ rSortCost = nRowEst + estLog(nRowEst);
109488
+ WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
109489
+ }
109490
+
109491
+ /* Compute successively longer WherePaths using the previous generation
109492
+ ** of WherePaths as the basis for the next. Keep track of the mxChoice
109493
+ ** best paths at each generation */
109494
+ for(iLoop=0; iLoop<nLoop; iLoop++){
109495
+ nTo = 0;
109496
+ for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
109497
+ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
109498
+ Bitmask maskNew;
109499
+ Bitmask revMask = 0;
109500
+ u8 isOrderedValid = pFrom->isOrderedValid;
109501
+ u8 isOrdered = pFrom->isOrdered;
109502
+ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
109503
+ if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
109504
+ /* At this point, pWLoop is a candidate to be the next loop.
109505
+ ** Compute its cost */
109506
+ rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
109507
+ rCost = whereCostAdd(rCost, pFrom->rCost);
109508
+ maskNew = pFrom->maskLoop | pWLoop->maskSelf;
109509
+ if( !isOrderedValid ){
109510
+ switch( wherePathSatisfiesOrderBy(pWInfo,
109511
+ pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
109512
+ iLoop, pWLoop, &revMask) ){
109513
+ case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
109514
+ isOrdered = 1;
109515
+ isOrderedValid = 1;
109516
+ break;
109517
+ case 0: /* No. pFrom+pWLoop will require a separate sort */
109518
+ isOrdered = 0;
109519
+ isOrderedValid = 1;
109520
+ rCost = whereCostAdd(rCost, rSortCost);
109521
+ break;
109522
+ default: /* Cannot tell yet. Try again on the next iteration */
109523
+ break;
109524
+ }
109525
+ }else{
109526
+ revMask = pFrom->revLoop;
109527
+ }
109528
+ /* Check to see if pWLoop should be added to the mxChoice best so far */
109529
+ for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
109530
+ if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
109531
+ testcase( jj==nTo-1 );
109532
+ break;
109533
+ }
109534
+ }
109535
+ if( jj>=nTo ){
109536
+ if( nTo>=mxChoice && rCost>=mxCost ){
109537
+#ifdef WHERETRACE_ENABLED
109538
+ if( sqlite3WhereTrace&0x4 ){
109539
+ sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
109540
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109541
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109542
+ }
109543
+#endif
109544
+ continue;
109545
+ }
109546
+ /* Add a new Path to the aTo[] set */
109547
+ if( nTo<mxChoice ){
109548
+ /* Increase the size of the aTo set by one */
109549
+ jj = nTo++;
109550
+ }else{
109551
+ /* New path replaces the prior worst to keep count below mxChoice */
109552
+ for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
109553
+ }
109554
+ pTo = &aTo[jj];
109555
+#ifdef WHERETRACE_ENABLED
109556
+ if( sqlite3WhereTrace&0x4 ){
109557
+ sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
109558
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109559
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109560
+ }
109561
+#endif
109562
+ }else{
109563
+ if( pTo->rCost<=rCost ){
109564
+#ifdef WHERETRACE_ENABLED
109565
+ if( sqlite3WhereTrace&0x4 ){
109566
+ sqlite3DebugPrintf(
109567
+ "Skip %s cost=%-3d order=%c",
109568
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109569
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109570
+ sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
109571
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109572
+ pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109573
+ }
109574
+#endif
109575
+ testcase( pTo->rCost==rCost );
109576
+ continue;
109577
+ }
109578
+ testcase( pTo->rCost==rCost+1 );
109579
+ /* A new and better score for a previously created equivalent path */
109580
+#ifdef WHERETRACE_ENABLED
109581
+ if( sqlite3WhereTrace&0x4 ){
109582
+ sqlite3DebugPrintf(
109583
+ "Update %s cost=%-3d order=%c",
109584
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109585
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109586
+ sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
109587
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109588
+ pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109589
+ }
109590
+#endif
109591
+ }
109592
+ /* pWLoop is a winner. Add it to the set of best so far */
109593
+ pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
109594
+ pTo->revLoop = revMask;
109595
+ pTo->nRow = pFrom->nRow + pWLoop->nOut;
109596
+ pTo->rCost = rCost;
109597
+ pTo->isOrderedValid = isOrderedValid;
109598
+ pTo->isOrdered = isOrdered;
109599
+ memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
109600
+ pTo->aLoop[iLoop] = pWLoop;
109601
+ if( nTo>=mxChoice ){
109602
+ mxCost = aTo[0].rCost;
109603
+ for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
109604
+ if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
109605
+ }
109606
+ }
109607
+ }
109608
+ }
109609
+
109610
+#ifdef WHERETRACE_ENABLED
109611
+ if( sqlite3WhereTrace>=2 ){
109612
+ sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
109613
+ for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
109614
+ sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
109615
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
109616
+ pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109617
+ if( pTo->isOrderedValid && pTo->isOrdered ){
109618
+ sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
109619
+ }else{
109620
+ sqlite3DebugPrintf("\n");
109621
+ }
109622
+ }
109623
+ }
109624
+#endif
109625
+
109626
+ /* Swap the roles of aFrom and aTo for the next generation */
109627
+ pFrom = aTo;
109628
+ aTo = aFrom;
109629
+ aFrom = pFrom;
109630
+ nFrom = nTo;
109631
+ }
109632
+
109633
+ if( nFrom==0 ){
109634
+ sqlite3ErrorMsg(pParse, "no query solution");
109635
+ sqlite3DbFree(db, pSpace);
109636
+ return SQLITE_ERROR;
109637
+ }
109638
+
109639
+ /* Find the lowest cost path. pFrom will be left pointing to that path */
109640
+ pFrom = aFrom;
109641
+ assert( nFrom==1 );
109642
+#if 0 /* The following is needed if nFrom is ever more than 1 */
109643
+ for(ii=1; ii<nFrom; ii++){
109644
+ if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
109645
+ }
109646
+#endif
109647
+ assert( pWInfo->nLevel==nLoop );
109648
+ /* Load the lowest cost path into pWInfo */
109649
+ for(iLoop=0; iLoop<nLoop; iLoop++){
109650
+ WhereLevel *pLevel = pWInfo->a + iLoop;
109651
+ pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
109652
+ pLevel->iFrom = pWLoop->iTab;
109653
+ pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
109654
+ }
109655
+ if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
109656
+ && pWInfo->pDistinct
109657
+ && nRowEst
109658
+ ){
109659
+ Bitmask notUsed;
109660
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinct, pFrom,
109661
+ WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
109662
+ if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109663
+ }
109664
+ if( pFrom->isOrdered ){
109665
+ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
109666
+ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109667
+ }else{
109668
+ pWInfo->bOBSat = 1;
109669
+ pWInfo->revMask = pFrom->revLoop;
109670
+ }
109671
+ }
109672
+ pWInfo->nRowOut = pFrom->nRow;
109673
+
109674
+ /* Free temporary memory and return success */
109675
+ sqlite3DbFree(db, pSpace);
109676
+ return SQLITE_OK;
109677
+}
109678
+
109679
+/*
109680
+** Most queries use only a single table (they are not joins) and have
109681
+** simple == constraints against indexed fields. This routine attempts
109682
+** to plan those simple cases using much less ceremony than the
109683
+** general-purpose query planner, and thereby yield faster sqlite3_prepare()
109684
+** times for the common case.
109685
+**
109686
+** Return non-zero on success, if this query can be handled by this
109687
+** no-frills query planner. Return zero if this query needs the
109688
+** general-purpose query planner.
109689
+*/
109690
+static int whereShortCut(WhereLoopBuilder *pBuilder){
109691
+ WhereInfo *pWInfo;
109692
+ struct SrcList_item *pItem;
109693
+ WhereClause *pWC;
109694
+ WhereTerm *pTerm;
109695
+ WhereLoop *pLoop;
109696
+ int iCur;
109697
+ int j;
109698
+ Table *pTab;
109699
+ Index *pIdx;
109700
+
109701
+ pWInfo = pBuilder->pWInfo;
109702
+ if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
109703
+ assert( pWInfo->pTabList->nSrc>=1 );
109704
+ pItem = pWInfo->pTabList->a;
109705
+ pTab = pItem->pTab;
109706
+ if( IsVirtual(pTab) ) return 0;
109707
+ if( pItem->zIndex ) return 0;
109708
+ iCur = pItem->iCursor;
109709
+ pWC = &pWInfo->sWC;
109710
+ pLoop = pBuilder->pNew;
109711
+ pLoop->wsFlags = 0;
109712
+ pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
109713
+ if( pTerm ){
109714
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
109715
+ pLoop->aLTerm[0] = pTerm;
109716
+ pLoop->nLTerm = 1;
109717
+ pLoop->u.btree.nEq = 1;
109718
+ /* TUNING: Cost of a rowid lookup is 10 */
109719
+ pLoop->rRun = 33; /* 33==whereCost(10) */
109720
+ }else{
109721
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109722
+ if( pIdx->onError==OE_None ) continue;
109723
+ for(j=0; j<pIdx->nColumn; j++){
109724
+ pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
109725
+ if( pTerm==0 ) break;
109726
+ whereLoopResize(pWInfo->pParse->db, pLoop, j);
109727
+ pLoop->aLTerm[j] = pTerm;
109728
+ }
109729
+ if( j!=pIdx->nColumn ) continue;
109730
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
109731
+ if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
109732
+ pLoop->wsFlags |= WHERE_IDX_ONLY;
109733
+ }
109734
+ pLoop->nLTerm = j;
109735
+ pLoop->u.btree.nEq = j;
109736
+ pLoop->u.btree.pIndex = pIdx;
109737
+ /* TUNING: Cost of a unique index lookup is 15 */
109738
+ pLoop->rRun = 39; /* 39==whereCost(15) */
109739
+ break;
109740
+ }
109741
+ }
109742
+ if( pLoop->wsFlags ){
109743
+ pLoop->nOut = (WhereCost)1;
109744
+ pWInfo->a[0].pWLoop = pLoop;
109745
+ pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
109746
+ pWInfo->a[0].iTabCur = iCur;
109747
+ pWInfo->nRowOut = 1;
109748
+ if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
109749
+ if( pWInfo->pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109750
+#ifdef SQLITE_DEBUG
109751
+ pLoop->cId = '0';
109752
+#endif
109753
+ return 1;
109754
+ }
109755
+ return 0;
109756
+}
109336109757
109337109758
/*
109338109759
** Generate the beginning of the loop used for WHERE clause processing.
109339109760
** The return value is a pointer to an opaque structure that contains
109340109761
** information needed to terminate the loop. Later, the calling routine
@@ -109410,19 +109831,10 @@
109410109831
** ORDER BY CLAUSE PROCESSING
109411109832
**
109412109833
** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109413109834
** if there is one. If there is no ORDER BY clause or if this routine
109414109835
** 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.
109424109836
*/
109425109837
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109426109838
Parse *pParse, /* The parser context */
109427109839
SrcList *pTabList, /* A list of all tables to be scanned */
109428109840
Expr *pWhere, /* The WHERE clause */
@@ -109434,22 +109846,21 @@
109434109846
int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
109435109847
int nTabList; /* Number of elements in pTabList */
109436109848
WhereInfo *pWInfo; /* Will become the return value of this function */
109437109849
Vdbe *v = pParse->pVdbe; /* The virtual database engine */
109438109850
Bitmask notReady; /* Cursors that are not yet positioned */
109439
- WhereBestIdx sWBI; /* Best index search context */
109851
+ WhereLoopBuilder sWLB; /* The WhereLoop builder */
109440109852
WhereMaskSet *pMaskSet; /* The expression mask set */
109441109853
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 */
109444109854
int ii; /* Loop counter */
109445109855
sqlite3 *db; /* Database connection */
109856
+ int rc; /* Return code */
109446109857
109447109858
109448109859
/* Variable initialization */
109449
- memset(&sWBI, 0, sizeof(sWBI));
109450
- sWBI.pParse = pParse;
109860
+ memset(&sWLB, 0, sizeof(sWLB));
109861
+ sWLB.pOrderBy = pOrderBy;
109451109862
109452109863
/* The number of tables in the FROM clause is limited by the number of
109453109864
** bits in a Bitmask
109454109865
*/
109455109866
testcase( pTabList->nSrc==BMS );
@@ -109472,49 +109883,59 @@
109472109883
** field (type Bitmask) it must be aligned on an 8-byte boundary on
109473109884
** some architectures. Hence the ROUND8() below.
109474109885
*/
109475109886
db = pParse->db;
109476109887
nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109477
- pWInfo = sqlite3DbMallocZero(db,
109478
- nByteWInfo +
109479
- sizeof(WhereClause) +
109480
- sizeof(WhereMaskSet)
109481
- );
109888
+ pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
109482109889
if( db->mallocFailed ){
109483109890
sqlite3DbFree(db, pWInfo);
109484109891
pWInfo = 0;
109485109892
goto whereBeginError;
109486109893
}
109487109894
pWInfo->nLevel = nTabList;
109488109895
pWInfo->pParse = pParse;
109489109896
pWInfo->pTabList = pTabList;
109897
+ pWInfo->pOrderBy = pOrderBy;
109898
+ pWInfo->pDistinct = pDistinct;
109490109899
pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
109491
- pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
109492109900
pWInfo->wctrlFlags = wctrlFlags;
109493109901
pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109494
- pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
109495
- sWBI.aLevel = pWInfo->a;
109902
+ pMaskSet = &pWInfo->sMaskSet;
109903
+ sWLB.pWInfo = pWInfo;
109904
+ sWLB.pWC = &pWInfo->sWC;
109905
+ sWLB.pNew = (WhereLoop*)&pWInfo->a[nTabList];
109906
+ whereLoopInit(sWLB.pNew);
109907
+#ifdef SQLITE_DEBUG
109908
+ sWLB.pNew->cId = '*';
109909
+#endif
109496109910
109497109911
/* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109498109912
** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109499109913
if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109500109914
109501109915
/* Split the WHERE clause into separate subexpressions where each
109502109916
** subexpression is separated by an AND operator.
109503109917
*/
109504109918
initMaskSet(pMaskSet);
109505
- whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
109919
+ whereClauseInit(&pWInfo->sWC, pWInfo);
109506109920
sqlite3ExprCodeConstants(pParse, pWhere);
109507
- whereSplit(sWBI.pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109921
+ whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109508109922
109509109923
/* Special case: a WHERE clause that is constant. Evaluate the
109510109924
** expression and either jump over all of the code or fall thru.
109511109925
*/
109512109926
if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109513109927
sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109514109928
pWhere = 0;
109515109929
}
109930
+
109931
+ /* Special case: No FROM clause
109932
+ */
109933
+ if( nTabList==0 ){
109934
+ if( pOrderBy ) pWInfo->bOBSat = 1;
109935
+ if( pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109936
+ }
109516109937
109517109938
/* Assign a bit from the bitmask to every term in the FROM clause.
109518109939
**
109519109940
** When assigning bitmask values to FROM clause cursors, it must be
109520109941
** the case that if X is the bitmask for the N-th FROM clause term then
@@ -109547,337 +109968,153 @@
109547109968
/* Analyze all of the subexpressions. Note that exprAnalyze() might
109548109969
** add new virtual terms onto the end of the WHERE clause. We do not
109549109970
** want to analyze these virtual terms, so start analyzing at the end
109550109971
** and work forward so that the added virtual terms are never processed.
109551109972
*/
109552
- exprAnalyzeAll(pTabList, sWBI.pWC);
109973
+ exprAnalyzeAll(pTabList, &pWInfo->sWC);
109553109974
if( db->mallocFailed ){
109554109975
goto whereBeginError;
109555109976
}
109977
+
109978
+ /* If the ORDER BY (or GROUP BY) clause contains references to general
109979
+ ** expressions, then we won't be able to satisfy it using indices, so
109980
+ ** go ahead and disable it now.
109981
+ */
109982
+ if( pOrderBy && pDistinct ){
109983
+ for(ii=0; ii<pOrderBy->nExpr; ii++){
109984
+ Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
109985
+ if( pExpr->op!=TK_COLUMN ){
109986
+ pWInfo->pOrderBy = pOrderBy = 0;
109987
+ break;
109988
+ }else if( pExpr->iColumn<0 ){
109989
+ break;
109990
+ }
109991
+ }
109992
+ }
109556109993
109557109994
/* Check if the DISTINCT qualifier, if there is one, is redundant.
109558109995
** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109559109996
** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109560109997
*/
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
- }
109998
+ if( pDistinct ){
109999
+ if( isDistinctRedundant(pParse,pTabList,&pWInfo->sWC,pDistinct) ){
110000
+ pDistinct = 0;
110001
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110002
+ }else if( pOrderBy==0 ){
110003
+ pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
110004
+ pWInfo->pOrderBy = pDistinct;
110005
+ }
110006
+ }
110007
+
110008
+ /* Construct the WhereLoop objects */
110009
+ WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
110010
+ if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
110011
+ rc = whereLoopAddAll(&sWLB);
110012
+ if( rc ) goto whereBeginError;
110013
+
110014
+ /* Display all of the WhereLoop objects if wheretrace is enabled */
110015
+#ifdef WHERETRACE_ENABLED
110016
+ if( sqlite3WhereTrace ){
110017
+ WhereLoop *p;
110018
+ int i = 0;
110019
+ static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
110020
+ "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
110021
+ for(p=pWInfo->pLoops; p; p=p->pNextLoop){
110022
+ p->cId = zLabel[(i++)%sizeof(zLabel)];
110023
+ whereLoopPrint(p, pTabList);
110024
+ }
110025
+ }
110026
+#endif
110027
+
110028
+ wherePathSolver(pWInfo, 0);
110029
+ if( db->mallocFailed ) goto whereBeginError;
110030
+ if( pWInfo->pOrderBy ){
110031
+ wherePathSolver(pWInfo, pWInfo->nRowOut+1);
110032
+ if( db->mallocFailed ) goto whereBeginError;
110033
+ }
110034
+ }
110035
+ if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
110036
+ pWInfo->revMask = (Bitmask)(-1);
110037
+ }
110038
+ if( pParse->nErr || NEVER(db->mallocFailed) ){
110039
+ goto whereBeginError;
110040
+ }
110041
+#ifdef WHERETRACE_ENABLED
110042
+ if( sqlite3WhereTrace ){
110043
+ int ii;
110044
+ sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
110045
+ if( pWInfo->bOBSat ){
110046
+ sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
110047
+ }
110048
+ switch( pWInfo->eDistinct ){
110049
+ case WHERE_DISTINCT_UNIQUE: {
110050
+ sqlite3DebugPrintf(" DISTINCT=unique");
110051
+ break;
110052
+ }
110053
+ case WHERE_DISTINCT_ORDERED: {
110054
+ sqlite3DebugPrintf(" DISTINCT=ordered");
110055
+ break;
110056
+ }
110057
+ case WHERE_DISTINCT_UNORDERED: {
110058
+ sqlite3DebugPrintf(" DISTINCT=unordered");
110059
+ break;
110060
+ }
110061
+ }
110062
+ sqlite3DebugPrintf("\n");
110063
+ for(ii=0; ii<nTabList; ii++){
110064
+ whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
110065
+ }
110066
+ }
110067
+#endif
110068
+ WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
110069
+ pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
109834110070
109835110071
/* If the caller is an UPDATE or DELETE statement that is requesting
109836110072
** to use a one-pass algorithm, determine if this is appropriate.
109837110073
** The one-pass algorithm only works if the WHERE clause constraints
109838110074
** the statement to update a single row.
109839110075
*/
109840110076
assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
109841
- if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
110077
+ if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
110078
+ && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
109842110079
pWInfo->okOnePass = 1;
109843
- pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
110080
+ pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
109844110081
}
109845110082
109846110083
/* Open all tables in the pTabList and any indices selected for
109847110084
** searching those tables.
109848110085
*/
109849110086
sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
109850110087
notReady = ~(Bitmask)0;
109851
- pWInfo->nRowOut = (double)1;
109852110088
for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
109853110089
Table *pTab; /* Table to open */
109854110090
int iDb; /* Index of database containing table/index */
109855110091
struct SrcList_item *pTabItem;
110092
+ WhereLoop *pLoop;
109856110093
109857110094
pTabItem = &pTabList->a[pLevel->iFrom];
109858110095
pTab = pTabItem->pTab;
109859
- pWInfo->nRowOut *= pLevel->plan.nRow;
109860110096
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110097
+ pLoop = pLevel->pWLoop;
109861110098
if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
109862110099
/* Do nothing */
109863110100
}else
109864110101
#ifndef SQLITE_OMIT_VIRTUALTABLE
109865
- if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
110102
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
109866110103
const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109867110104
int iCur = pTabItem->iCursor;
109868110105
sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
109869110106
}else if( IsVirtual(pTab) ){
109870110107
/* noop */
109871110108
}else
109872110109
#endif
109873
- if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110110
+ if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
109874110111
&& (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
109875110112
int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
109876110113
sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
109877
- testcase( pTab->nCol==BMS-1 );
109878
- testcase( pTab->nCol==BMS );
110114
+ testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
110115
+ testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
109879110116
if( !pWInfo->okOnePass && pTab->nCol<BMS ){
109880110117
Bitmask b = pTabItem->colUsed;
109881110118
int n = 0;
109882110119
for(; b; b=b>>1, n++){}
109883110120
sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
@@ -109886,26 +110123,27 @@
109886110123
}
109887110124
}else{
109888110125
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109889110126
}
109890110127
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109891
- if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
109892
- constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
110128
+ if( (pLoop->wsFlags & WHERE_TEMP_INDEX)!=0 ){
110129
+ constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
109893110130
}else
109894110131
#endif
109895
- if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
109896
- Index *pIx = pLevel->plan.u.pIdx;
110132
+ if( pLoop->wsFlags & WHERE_INDEXED ){
110133
+ Index *pIx = pLoop->u.btree.pIndex;
109897110134
KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
109898
- int iIndexCur = pLevel->iIdxCur;
110135
+ /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
110136
+ int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
109899110137
assert( pIx->pSchema==pTab->pSchema );
109900110138
assert( iIndexCur>=0 );
109901110139
sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
109902110140
(char*)pKey, P4_KEYINFO_HANDOFF);
109903110141
VdbeComment((v, "%s", pIx->zName));
109904110142
}
109905110143
sqlite3CodeVerifySchema(pParse, iDb);
109906
- notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
110144
+ notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
109907110145
}
109908110146
pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
109909110147
if( db->mallocFailed ) goto whereBeginError;
109910110148
109911110149
/* Generate the code to do the search. Each iteration of the for
@@ -109914,70 +110152,15 @@
109914110152
*/
109915110153
notReady = ~(Bitmask)0;
109916110154
for(ii=0; ii<nTabList; ii++){
109917110155
pLevel = &pWInfo->a[ii];
109918110156
explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
109919
- notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
110157
+ notReady = codeOneLoopStart(pWInfo, ii, notReady);
109920110158
pWInfo->iContinue = pLevel->addrCont;
109921110159
}
109922110160
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
- */
110161
+ /* Done. */
109979110162
return pWInfo;
109980110163
109981110164
/* Jump here if malloc fails */
109982110165
whereBeginError:
109983110166
if( pWInfo ){
@@ -109994,24 +110177,26 @@
109994110177
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
109995110178
Parse *pParse = pWInfo->pParse;
109996110179
Vdbe *v = pParse->pVdbe;
109997110180
int i;
109998110181
WhereLevel *pLevel;
110182
+ WhereLoop *pLoop;
109999110183
SrcList *pTabList = pWInfo->pTabList;
110000110184
sqlite3 *db = pParse->db;
110001110185
110002110186
/* Generate loop termination code.
110003110187
*/
110004110188
sqlite3ExprCacheClear(pParse);
110005110189
for(i=pWInfo->nLevel-1; i>=0; i--){
110006110190
pLevel = &pWInfo->a[i];
110191
+ pLoop = pLevel->pWLoop;
110007110192
sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110008110193
if( pLevel->op!=OP_Noop ){
110009110194
sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110010110195
sqlite3VdbeChangeP5(v, pLevel->p5);
110011110196
}
110012
- if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110197
+ if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110013110198
struct InLoop *pIn;
110014110199
int j;
110015110200
sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110016110201
for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110017110202
sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
@@ -110022,16 +110207,16 @@
110022110207
}
110023110208
sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110024110209
if( pLevel->iLeftJoin ){
110025110210
int addr;
110026110211
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 ){
110212
+ assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110213
+ || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
110214
+ if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
110030110215
sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110031110216
}
110032
- if( pLevel->iIdxCur>=0 ){
110217
+ if( pLoop->wsFlags & WHERE_INDEXED ){
110033110218
sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110034110219
}
110035110220
if( pLevel->op==OP_Return ){
110036110221
sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110037110222
}else{
@@ -110052,42 +110237,41 @@
110052110237
for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110053110238
Index *pIdx = 0;
110054110239
struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110055110240
Table *pTab = pTabItem->pTab;
110056110241
assert( pTab!=0 );
110242
+ pLoop = pLevel->pWLoop;
110057110243
if( (pTab->tabFlags & TF_Ephemeral)==0
110058110244
&& pTab->pSelect==0
110059110245
&& (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110060110246
){
110061
- int ws = pLevel->plan.wsFlags;
110247
+ int ws = pLoop->wsFlags;
110062110248
if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110063110249
sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110064110250
}
110065
- if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
110251
+ if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_TEMP_INDEX))==0 ){
110066110252
sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110067110253
}
110068110254
}
110069110255
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.
110256
+ /* If this scan uses an index, make VDBE code substitutions to read data
110257
+ ** from the index instead of from the table where possible. In some cases
110258
+ ** this optimization prevents the table from ever being read, which can
110259
+ ** yield a significant performance boost.
110076110260
**
110077110261
** Calls to the code generator in between sqlite3WhereBegin and
110078110262
** sqlite3WhereEnd will have created code that references the table
110079110263
** directly. This loop scans all that code looking for opcodes
110080110264
** that reference the table and converts them into opcodes that
110081110265
** reference the index.
110082110266
*/
110083
- if( pLevel->plan.wsFlags & WHERE_INDEXED ){
110084
- pIdx = pLevel->plan.u.pIdx;
110085
- }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
110267
+ if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
110268
+ pIdx = pLoop->u.btree.pIndex;
110269
+ }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
110086110270
pIdx = pLevel->u.pCovidx;
110087110271
}
110088
- if( pIdx && !db->mallocFailed){
110272
+ if( pIdx && !db->mallocFailed ){
110089110273
int k, j, last;
110090110274
VdbeOp *pOp;
110091110275
110092110276
pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110093110277
last = sqlite3VdbeCurrentAddr(v);
@@ -110099,12 +110283,11 @@
110099110283
pOp->p2 = j;
110100110284
pOp->p1 = pLevel->iIdxCur;
110101110285
break;
110102110286
}
110103110287
}
110104
- assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110105
- || j<pIdx->nColumn );
110288
+ assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
110106110289
}else if( pOp->opcode==OP_Rowid ){
110107110290
pOp->p1 = pLevel->iIdxCur;
110108110291
pOp->opcode = OP_IdxRowid;
110109110292
}
110110110293
}
@@ -115480,11 +115663,11 @@
115480115663
}
115481115664
115482115665
/*
115483115666
** Another built-in collating sequence: NOCASE.
115484115667
**
115485
-** This collating sequence is intended to be used for "case independant
115668
+** This collating sequence is intended to be used for "case independent
115486115669
** comparison". SQLite's knowledge of upper and lower case equivalents
115487115670
** extends only to the 26 characters used in the English language.
115488115671
**
115489115672
** At the moment there is only a UTF-8 implementation.
115490115673
*/
@@ -115627,16 +115810,10 @@
115627115810
"statements or unfinished backups");
115628115811
sqlite3_mutex_leave(db->mutex);
115629115812
return SQLITE_BUSY;
115630115813
}
115631115814
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
-
115638115815
#ifdef SQLITE_ENABLE_SQLLOG
115639115816
if( sqlite3GlobalConfig.xSqllog ){
115640115817
/* Closing the handle. Fourth parameter is passed the value 2. */
115641115818
sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115642115819
}
@@ -115686,10 +115863,16 @@
115686115863
/* If we reach this point, it means that the database connection has
115687115864
** closed all sqlite3_stmt and sqlite3_backup objects and has been
115688115865
** passed to sqlite3_close (meaning that it is a zombie). Therefore,
115689115866
** go ahead and free all resources.
115690115867
*/
115868
+
115869
+ /* If a transaction is open, roll it back. This also ensures that if
115870
+ ** any database schemas have been modified by an uncommitted transaction
115871
+ ** they are reset. And that the required b-tree mutex is held to make
115872
+ ** the pager rollback and schema reset an atomic operation. */
115873
+ sqlite3RollbackAll(db, SQLITE_OK);
115691115874
115692115875
/* Free any outstanding Savepoint structures. */
115693115876
sqlite3CloseSavepoints(db);
115694115877
115695115878
/* Close all database connections */
@@ -115787,19 +115970,26 @@
115787115970
SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115788115971
int i;
115789115972
int inTrans = 0;
115790115973
assert( sqlite3_mutex_held(db->mutex) );
115791115974
sqlite3BeginBenignMalloc();
115975
+
115976
+ /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
115977
+ ** This is important in case the transaction being rolled back has
115978
+ ** modified the database schema. If the b-tree mutexes are not taken
115979
+ ** here, then another shared-cache connection might sneak in between
115980
+ ** the database rollback and schema reset, which can cause false
115981
+ ** corruption reports in some cases. */
115792115982
sqlite3BtreeEnterAll(db);
115983
+
115793115984
for(i=0; i<db->nDb; i++){
115794115985
Btree *p = db->aDb[i].pBt;
115795115986
if( p ){
115796115987
if( sqlite3BtreeIsInTrans(p) ){
115797115988
inTrans = 1;
115798115989
}
115799115990
sqlite3BtreeRollback(p, tripCode);
115800
- db->aDb[i].inTrans = 0;
115801115991
}
115802115992
}
115803115993
sqlite3VtabRollback(db);
115804115994
sqlite3EndBenignMalloc();
115805115995
@@ -117562,12 +117752,10 @@
117562117752
/*
117563117753
** Test to see whether or not the database connection is in autocommit
117564117754
** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
117565117755
** by default. Autocommit is disabled by a BEGIN statement and reenabled
117566117756
** by the next COMMIT or ROLLBACK.
117567
-**
117568
-******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
117569117757
*/
117570117758
SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117571117759
return db->autoCommit;
117572117760
}
117573117761
@@ -119051,10 +119239,22 @@
119051119239
119052119240
#endif /* _FTS3_HASH_H_ */
119053119241
119054119242
/************** End of fts3_hash.h *******************************************/
119055119243
/************** Continuing where we left off in fts3Int.h ********************/
119244
+
119245
+/*
119246
+** This constant determines the maximum depth of an FTS expression tree
119247
+** that the library will create and use. FTS uses recursion to perform
119248
+** various operations on the query tree, so the disadvantage of a large
119249
+** limit is that it may allow very large queries to use large amounts
119250
+** of stack space (perhaps causing a stack overflow).
119251
+*/
119252
+#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
119253
+# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
119254
+#endif
119255
+
119056119256
119057119257
/*
119058119258
** This constant controls how often segments are merged. Once there are
119059119259
** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119060119260
** segment of level N+1.
@@ -120709,11 +120909,11 @@
120709120909
/* By default use a full table scan. This is an expensive option,
120710120910
** so search through the constraints to see if a more efficient
120711120911
** strategy is possible.
120712120912
*/
120713120913
pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120714
- pInfo->estimatedCost = 500000;
120914
+ pInfo->estimatedCost = 5000000;
120715120915
for(i=0; i<pInfo->nConstraint; i++){
120716120916
struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120717120917
if( pCons->usable==0 ) continue;
120718120918
120719120919
/* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
@@ -122270,15 +122470,11 @@
122270122470
);
122271122471
if( rc!=SQLITE_OK ){
122272122472
return rc;
122273122473
}
122274122474
122275
- rc = sqlite3Fts3ReadLock(p);
122276
- if( rc!=SQLITE_OK ) return rc;
122277
-
122278122475
rc = fts3EvalStart(pCsr);
122279
-
122280122476
sqlite3Fts3SegmentsClose(p);
122281122477
if( rc!=SQLITE_OK ) return rc;
122282122478
pCsr->pNextId = pCsr->aDoclist;
122283122479
pCsr->iPrevId = 0;
122284122480
}
@@ -126129,30 +126325,30 @@
126129126325
int iDefaultCol, /* Default column to query */
126130126326
const char *z, int n, /* Text of MATCH query */
126131126327
Fts3Expr **ppExpr, /* OUT: Parsed query structure */
126132126328
char **pzErr /* OUT: Error message (sqlite3_malloc) */
126133126329
){
126134
- static const int MAX_EXPR_DEPTH = 12;
126135126330
int rc = fts3ExprParseUnbalanced(
126136126331
pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126137126332
);
126138126333
126139126334
/* Rebalance the expression. And check that its depth does not exceed
126140
- ** MAX_EXPR_DEPTH. */
126335
+ ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
126141126336
if( rc==SQLITE_OK && *ppExpr ){
126142
- rc = fts3ExprBalance(ppExpr, MAX_EXPR_DEPTH);
126337
+ rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126143126338
if( rc==SQLITE_OK ){
126144
- rc = fts3ExprCheckDepth(*ppExpr, MAX_EXPR_DEPTH);
126339
+ rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126145126340
}
126146126341
}
126147126342
126148126343
if( rc!=SQLITE_OK ){
126149126344
sqlite3Fts3ExprFree(*ppExpr);
126150126345
*ppExpr = 0;
126151126346
if( rc==SQLITE_TOOBIG ){
126152126347
*pzErr = sqlite3_mprintf(
126153
- "FTS expression tree is too large (maximum depth %d)", MAX_EXPR_DEPTH
126348
+ "FTS expression tree is too large (maximum depth %d)",
126349
+ SQLITE_FTS3_MAX_EXPR_DEPTH
126154126350
);
126155126351
rc = SQLITE_ERROR;
126156126352
}else if( rc==SQLITE_ERROR ){
126157126353
*pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126158126354
}
@@ -129110,41 +129306,34 @@
129110129306
*pRC = rc;
129111129307
}
129112129308
129113129309
129114129310
/*
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);
129311
+** This function ensures that the caller has obtained an exclusive
129312
+** shared-cache table-lock on the %_segdir table. This is required before
129313
+** writing data to the fts3 table. If this lock is not acquired first, then
129314
+** the caller may end up attempting to take this lock as part of committing
129315
+** a transaction, causing SQLite to return SQLITE_LOCKED or
129316
+** LOCKED_SHAREDCACHEto a COMMIT command.
129317
+**
129318
+** It is best to avoid this because if FTS3 returns any error when
129319
+** committing a transaction, the whole transaction will be rolled back.
129320
+** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
129321
+** It can still happen if the user locks the underlying tables directly
129322
+** instead of accessing them via FTS.
129323
+*/
129324
+static int fts3Writelock(Fts3Table *p){
129325
+ int rc = SQLITE_OK;
129326
+
129327
+ if( p->nPendingData==0 ){
129328
+ sqlite3_stmt *pStmt;
129329
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
129139129330
if( rc==SQLITE_OK ){
129140129331
sqlite3_bind_null(pStmt, 1);
129141129332
sqlite3_step(pStmt);
129142129333
rc = sqlite3_reset(pStmt);
129143129334
}
129144
- }else{
129145
- rc = SQLITE_OK;
129146129335
}
129147129336
129148129337
return rc;
129149129338
}
129150129339
@@ -133918,10 +134107,13 @@
133918134107
goto update_out;
133919134108
}
133920134109
aSzIns = &aSzDel[p->nColumn+1];
133921134110
memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
133922134111
134112
+ rc = fts3Writelock(p);
134113
+ if( rc!=SQLITE_OK ) goto update_out;
134114
+
133923134115
/* If this is an INSERT operation, or an UPDATE that modifies the rowid
133924134116
** value, then this operation requires constraint handling.
133925134117
**
133926134118
** If the on-conflict mode is REPLACE, this means that the existing row
133927134119
** should be deleted from the database before inserting the new row. Or,
@@ -136051,32 +136243,31 @@
136051136243
0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136052136244
0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136053136245
0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136054136246
0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136055136247
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,
136248
+ 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
136249
+ 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
136250
+ 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
136251
+ 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
136252
+ 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
136253
+ 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
136254
+ 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
136255
+ 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
136256
+ 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
136257
+ 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
136258
+ 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
136259
+ 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
136260
+ 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
136261
+ 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
136262
+ 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
136263
+ 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
136264
+ 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
136265
+ 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
136266
+ 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
136267
+ 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
136268
+ 0x380400F0,
136078136269
};
136079136270
static const unsigned int aAscii[4] = {
136080136271
0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136081136272
};
136082136273
@@ -139705,11 +139896,11 @@
139705139896
** operator) using the ICU uregex_XX() APIs.
139706139897
**
139707139898
** * Implementations of the SQL scalar upper() and lower() functions
139708139899
** for case mapping.
139709139900
**
139710
-** * Integration of ICU and SQLite collation seqences.
139901
+** * Integration of ICU and SQLite collation sequences.
139711139902
**
139712139903
** * An implementation of the LIKE operator that uses ICU to
139713139904
** provide case-independent matching.
139714139905
*/
139715139906
139716139907
--- 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";
@@ -22929,17 +22845,10 @@
22929 ** * Definitions of sqlite3_vfs objects for all locking methods
22930 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
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
22943 ** control:
22944 **
22945 ** 1. POSIX locking (the default),
@@ -26866,19 +26775,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 +28157,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 +30712,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 +33437,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 +33523,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 +33568,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 +34877,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 +37136,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 +42460,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 +43426,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 +44836,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 +45411,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 +50681,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 +52624,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 +57967,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 +61858,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 +63927,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 +64552,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 +64579,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 +68178,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 +72133,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 +73408,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 +74948,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 +76720,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 +76770,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 +80170,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 +83358,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 +84778,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 +84837,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 +85269,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 +87284,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 +87943,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 +88131,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 +94049,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 +94588,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 +95046,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 +95061,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 +95698,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 +95720,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 +96084,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 +97498,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 +97513,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 +97708,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 +99859,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 +100020,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 +100213,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 +100241,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 +100260,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 +100294,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 +100376,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 +100660,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 +102020,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 +102471,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 +104308,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 +104515,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 +104548,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 +104577,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 +104639,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 +104706,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 +104830,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 +104871,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 +104911,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 +104923,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 +104936,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 +104956,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 +105012,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 +105039,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 +105097,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 +105253,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 +105506,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 +105529,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 +105555,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 +105575,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 +105640,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 +105659,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 +105708,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 +105757,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 +105768,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 +106053,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 +106084,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 +106151,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 +106268,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 +106283,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 +106319,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 +106334,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 +106393,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 +106406,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 +106429,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 +106456,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 +106506,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 +106561,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 +106577,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 +106602,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 +106845,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 +106883,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 +106933,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 +106952,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 +106982,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 +106998,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 +107101,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 +107119,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 +107138,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 +107209,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 +107246,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 +107320,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 +107339,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 +107366,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 +107393,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 +107440,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 +107462,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 +107506,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 +107547,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 +107640,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 +107695,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 +107712,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 +107736,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 +107764,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 +107857,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 +107878,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 +107948,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 +107967,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 +107989,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 +108040,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 +108073,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 +108105,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 +108166,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 +108200,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 +109831,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 +109846,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 +109883,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 +109968,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 +110123,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 +110152,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 +110177,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 +110207,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 +110237,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 +110283,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 +115663,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 +115810,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 +115863,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 +115970,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 +117752,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 +119239,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 +120909,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 +122470,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 +126325,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 +129306,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 +134107,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 +136243,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 +139896,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-20 14:17:39 d94db3fd921890ab1d6414ab629410ae50779686"
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";
@@ -22929,17 +22845,10 @@
22845 ** * Definitions of sqlite3_vfs objects for all locking methods
22846 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
22847 */
22848 #if SQLITE_OS_UNIX /* This file is used on unix only */
22849
 
 
 
 
 
 
 
22850 /*
22851 ** There are various methods for file locking used for concurrency
22852 ** control:
22853 **
22854 ** 1. POSIX locking (the default),
@@ -26866,19 +26775,23 @@
26775 }
26776 return SQLITE_OK;
26777 }
26778 case SQLITE_FCNTL_MMAP_SIZE: {
26779 i64 newLimit = *(i64*)pArg;
26780 int rc = SQLITE_OK;
26781 if( newLimit>sqlite3GlobalConfig.mxMmap ){
26782 newLimit = sqlite3GlobalConfig.mxMmap;
26783 }
26784 *(i64*)pArg = pFile->mmapSizeMax;
26785 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
26786 pFile->mmapSizeMax = newLimit;
26787 if( pFile->mmapSize>0 ){
26788 unixUnmapfile(pFile);
26789 rc = unixMapfile(pFile, -1);
26790 }
26791 }
26792 return rc;
26793 }
26794 #ifdef SQLITE_DEBUG
26795 /* The pager calls this method to signal that it has done
26796 ** a rollback and that the database is therefore unchanged and
26797 ** it hence it is OK for the transaction change counter to be
@@ -28244,11 +28157,11 @@
28157 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28158 pNew->h = h;
28159 pNew->pVfs = pVfs;
28160 pNew->zPath = zFilename;
28161 pNew->ctrlFlags = (u8)ctrlFlags;
28162 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28163 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28164 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28165 pNew->ctrlFlags |= UNIXFILE_PSOW;
28166 }
28167 if( strcmp(pVfs->zName,"unix-excl")==0 ){
@@ -30799,17 +30712,10 @@
30712 ** This file mapping API is common to both Win32 and WinRT.
30713 */
30714 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30715 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30716
 
 
 
 
 
 
 
30717 /*
30718 ** Some Microsoft compilers lack this definition.
30719 */
30720 #ifndef INVALID_FILE_ATTRIBUTES
30721 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
@@ -33531,10 +33437,13 @@
33437 }
33438 }
33439
33440 /* Forward declaration */
33441 static int getTempname(int nBuf, char *zBuf);
33442 #if SQLITE_MAX_MMAP_SIZE>0
33443 static int winMapfile(winFile*, sqlite3_int64);
33444 #endif
33445
33446 /*
33447 ** Control and query of the open file handle.
33448 */
33449 static int winFileControl(sqlite3_file *id, int op, void *pArg){
@@ -33614,17 +33523,24 @@
33523 return SQLITE_OK;
33524 }
33525 #if SQLITE_MAX_MMAP_SIZE>0
33526 case SQLITE_FCNTL_MMAP_SIZE: {
33527 i64 newLimit = *(i64*)pArg;
33528 int rc = SQLITE_OK;
33529 if( newLimit>sqlite3GlobalConfig.mxMmap ){
33530 newLimit = sqlite3GlobalConfig.mxMmap;
33531 }
33532 *(i64*)pArg = pFile->mmapSizeMax;
33533 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33534 pFile->mmapSizeMax = newLimit;
33535 if( pFile->mmapSize>0 ){
33536 (void)winUnmapfile(pFile);
33537 rc = winMapfile(pFile, -1);
33538 }
33539 }
33540 OSTRACE(("FCNTL file=%p, rc=%d\n", pFile->h, rc));
33541 return rc;
33542 }
33543 #endif
33544 }
33545 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
33546 return SQLITE_NOTFOUND;
@@ -33652,19 +33568,19 @@
33568 winFile *p = (winFile*)id;
33569 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
33570 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
33571 }
33572
 
 
33573 /*
33574 ** Windows will only let you create file view mappings
33575 ** on allocation size granularity boundaries.
33576 ** During sqlite3_os_init() we do a GetSystemInfo()
33577 ** to get the granularity size.
33578 */
33579 SYSTEM_INFO winSysInfo;
33580
33581 #ifndef SQLITE_OMIT_WAL
33582
33583 /*
33584 ** Helper functions to obtain and relinquish the global mutex. The
33585 ** global mutex is used to protect the winLockInfo objects used by
33586 ** this file, all of which may be shared by multiple threads.
@@ -34961,11 +34877,11 @@
34877 #if SQLITE_MAX_MMAP_SIZE>0
34878 pFile->hMap = NULL;
34879 pFile->pMapRegion = 0;
34880 pFile->mmapSize = 0;
34881 pFile->mmapSizeActual = 0;
34882 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34883 #endif
34884
34885 OpenCounter(+1);
34886 return rc;
34887 }
@@ -37220,11 +37136,11 @@
37136 PCache1 *pCache; /* The newly created page cache */
37137 PGroup *pGroup; /* The group the new page cache will belong to */
37138 int sz; /* Bytes of memory required to allocate the new cache */
37139
37140 /*
37141 ** The separateCache variable is true if each PCache has its own private
37142 ** PGroup. In other words, separateCache is true for mode (1) where no
37143 ** mutexing is required.
37144 **
37145 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37146 **
@@ -42544,11 +42460,12 @@
42460 /* Before the first write, give the VFS a hint of what the final
42461 ** file size will be.
42462 */
42463 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42464 if( rc==SQLITE_OK
42465 && pPager->dbHintSize<pPager->dbSize
42466 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
42467 ){
42468 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42469 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42470 pPager->dbHintSize = pPager->dbSize;
42471 }
@@ -43509,11 +43426,11 @@
43426 ** requested page is not already stored in the cache, then no
43427 ** actual disk read occurs. In this case the memory image of the
43428 ** page is initialized to all zeros.
43429 **
43430 ** If noContent is true, it means that we do not care about the contents
43431 ** of the page. This occurs in two scenarios:
43432 **
43433 ** a) When reading a free-list leaf page from the database, and
43434 **
43435 ** b) When a savepoint is being rolled back and we need to load
43436 ** a new page into the cache to be filled with the data read
@@ -44919,11 +44836,31 @@
44836 pagerReportSize(pPager);
44837 }
44838 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44839 return pPager->pCodec;
44840 }
44841
44842 /*
44843 ** This function is called by the wal module when writing page content
44844 ** into the log file.
44845 **
44846 ** This function returns a pointer to a buffer containing the encrypted
44847 ** page content. If a malloc fails, this function may return NULL.
44848 */
44849 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44850 void *aData = 0;
44851 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44852 return aData;
44853 }
44854
44855 /*
44856 ** Return the current pager state
44857 */
44858 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
44859 return pPager->eState;
44860 }
44861 #endif /* SQLITE_HAS_CODEC */
44862
44863 #ifndef SQLITE_OMIT_AUTOVACUUM
44864 /*
44865 ** Move the page pPg to location pgno in the file.
44866 **
@@ -45474,25 +45411,10 @@
45411 assert( pPager->eState==PAGER_READER );
45412 return sqlite3WalFramesize(pPager->pWal);
45413 }
45414 #endif
45415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45416 #endif /* SQLITE_OMIT_DISKIO */
45417
45418 /************** End of pager.c ***********************************************/
45419 /************** Begin file wal.c *********************************************/
45420 /*
@@ -50759,11 +50681,11 @@
50681 if( rc ) return rc;
50682 top = get2byteNotZero(&data[hdr+5]);
50683 }else if( gap+2<=top ){
50684 /* Search the freelist looking for a free slot big enough to satisfy
50685 ** the request. The allocation is made from the first free slot in
50686 ** the list that is large enough to accommodate it.
50687 */
50688 int pc, addr;
50689 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50690 int size; /* Size of the free slot */
50691 if( pc>usableSize-4 || pc<addr+4 ){
@@ -52702,11 +52624,11 @@
52624 return rc;
52625 }
52626
52627 /*
52628 ** This routine is called prior to sqlite3PagerCommit when a transaction
52629 ** is committed for an auto-vacuum database.
52630 **
52631 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52632 ** the database file should be truncated to during the commit process.
52633 ** i.e. the database has been reorganized so that only the first *pnTrunc
52634 ** pages are in use.
@@ -58045,16 +57967,10 @@
57967 *************************************************************************
57968 ** This file contains the implementation of the sqlite3_backup_XXX()
57969 ** API functions and the related features.
57970 */
57971
 
 
 
 
 
 
57972 /*
57973 ** Structure allocated for each backup operation.
57974 */
57975 struct sqlite3_backup {
57976 sqlite3* pDestDb; /* Destination database handle */
@@ -61942,11 +61858,11 @@
61858 /*
61859 ** If the Vdbe passed as the first argument opened a statement-transaction,
61860 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61861 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61862 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61863 ** statement transaction is committed.
61864 **
61865 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
61866 ** Otherwise SQLITE_OK.
61867 */
61868 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
@@ -64011,17 +63927,10 @@
63927 int iType = sqlite3_value_type( columnMem(pStmt,i) );
63928 columnMallocFailure(pStmt);
63929 return iType;
63930 }
63931
 
 
 
 
 
 
 
63932 /*
63933 ** Convert the N-th element of pStmt->pColName[] into a string using
63934 ** xFunc() then return that string. If N is out of range, return 0.
63935 **
63936 ** There are up to 5 names for each column. useType determines which
@@ -64643,18 +64552,18 @@
64552 pVar = &utf8;
64553 }
64554 #endif
64555 nOut = pVar->n;
64556 #ifdef SQLITE_TRACE_SIZE_LIMIT
64557 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
64558 nOut = SQLITE_TRACE_SIZE_LIMIT;
64559 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
64560 }
64561 #endif
64562 sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
64563 #ifdef SQLITE_TRACE_SIZE_LIMIT
64564 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64565 #endif
64566 #ifndef SQLITE_OMIT_UTF16
64567 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
64568 #endif
64569 }else if( pVar->flags & MEM_Zero ){
@@ -64670,11 +64579,11 @@
64579 for(i=0; i<nOut; i++){
64580 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64581 }
64582 sqlite3StrAccumAppend(&out, "'", 1);
64583 #ifdef SQLITE_TRACE_SIZE_LIMIT
64584 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64585 #endif
64586 }
64587 }
64588 }
64589 return sqlite3StrAccumFinish(&out);
@@ -68269,12 +68178,12 @@
68178 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
68179 ** obtained on the database file when a write-transaction is started. No
68180 ** other process can start another write transaction while this transaction is
68181 ** underway. Starting a write transaction also creates a rollback journal. A
68182 ** write transaction must be started before any changes can be made to the
68183 ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
68184 ** also obtained on the file.
68185 **
68186 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68187 ** true (this flag is set if the Vdbe may modify more than one row and may
68188 ** throw an ABORT exception), a statement transaction may also be opened.
68189 ** More specifically, a statement transaction is opened iff the database
@@ -72224,11 +72133,11 @@
72133 **
72134 ** For the purposes of this comparison, EOF is considered greater than any
72135 ** other key value. If the keys are equal (only possible with two EOF
72136 ** values), it doesn't matter which index is stored.
72137 **
72138 ** The (N/4) elements of aTree[] that precede the final (N/2) described
72139 ** above contains the index of the smallest of each block of 4 iterators.
72140 ** And so on. So that aTree[1] contains the index of the iterator that
72141 ** currently points to the smallest key value. aTree[0] is unused.
72142 **
72143 ** Example:
@@ -73499,16 +73408,10 @@
73408 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
73409 ** memory allocators.
73410 */
73411 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73412
 
 
 
 
 
 
73413 /*
73414 ** The rollback journal is composed of a linked list of these structures.
73415 */
73416 struct FileChunk {
73417 FileChunk *pNext; /* Next chunk in the journal */
@@ -75045,12 +74948,12 @@
74948 **
74949 ** Minor point: If this is the case, then the expression will be
74950 ** re-evaluated for each reference to it.
74951 */
74952 sNC.pEList = p->pEList;
 
74953 sNC.ncFlags |= NC_AsMaybe;
74954 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
74955 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
74956 sNC.ncFlags &= ~NC_AsMaybe;
74957
74958 /* The ORDER BY and GROUP BY clauses may not refer to terms in
74959 ** outer queries
@@ -76817,19 +76720,19 @@
76720
76721 if( eType==0 ){
76722 /* Could not found an existing table or index to use as the RHS b-tree.
76723 ** We will have to generate an ephemeral table to do the job.
76724 */
76725 u32 savedNQueryLoop = pParse->nQueryLoop;
76726 int rMayHaveNull = 0;
76727 eType = IN_INDEX_EPH;
76728 if( prNotFound ){
76729 *prNotFound = rMayHaveNull = ++pParse->nMem;
76730 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76731 }else{
76732 testcase( pParse->nQueryLoop>0 );
76733 pParse->nQueryLoop = 0;
76734 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
76735 eType = IN_INDEX_ROWID;
76736 }
76737 }
76738 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
@@ -76867,11 +76770,11 @@
76770 ** the register given by rMayHaveNull to NULL. Calling routines will take
76771 ** care of changing this register value to non-NULL if the RHS is NULL-free.
76772 **
76773 ** If rMayHaveNull is zero, that means that the subquery is being used
76774 ** for membership testing only. There is no need to initialize any
76775 ** registers to indicate the presence or absence of NULLs on the RHS.
76776 **
76777 ** For a SELECT or EXISTS operator, return the register that holds the
76778 ** result. For IN operators or if an error occurs, the return value is 0.
76779 */
76780 #ifndef SQLITE_OMIT_SUBQUERY
@@ -80267,11 +80170,11 @@
80170 **
80171 ** Additional tables might be added in future releases of SQLite.
80172 ** The sqlite_stat2 table is not created or used unless the SQLite version
80173 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80174 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
80175 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
80176 ** created and used by SQLite versions 3.7.9 and later and with
80177 ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
80178 ** is a superset of sqlite_stat2.
80179 **
80180 ** Format of sqlite_stat1:
@@ -83455,10 +83358,11 @@
83358 zColl = sqlite3NameFromToken(db, pToken);
83359 if( !zColl ) return;
83360
83361 if( sqlite3LocateCollSeq(pParse, zColl) ){
83362 Index *pIdx;
83363 sqlite3DbFree(db, p->aCol[i].zColl);
83364 p->aCol[i].zColl = zColl;
83365
83366 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83367 ** then an index may have been created on this column before the
83368 ** collation type was added. Correct this if it is the case.
@@ -84874,10 +84778,11 @@
84778 zExtra = (char *)(&pIndex->zName[nName+1]);
84779 memcpy(pIndex->zName, zName, nName+1);
84780 pIndex->pTable = pTab;
84781 pIndex->nColumn = pList->nExpr;
84782 pIndex->onError = (u8)onError;
84783 pIndex->uniqNotNull = onError==OE_Abort;
84784 pIndex->autoIndex = (u8)(pName==0);
84785 pIndex->pSchema = db->aDb[iDb].pSchema;
84786 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84787
84788 /* Check to see if we should honor DESC requests on index columns
@@ -84932,10 +84837,11 @@
84837 goto exit_create_index;
84838 }
84839 pIndex->azColl[i] = zColl;
84840 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
84841 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84842 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
84843 }
84844 sqlite3DefaultRowEst(pIndex);
84845
84846 if( pTab==pParse->pNewTable ){
84847 /* This routine has been called to create an automatic index as a
@@ -85363,19 +85269,19 @@
85269 assert( db->mallocFailed );
85270 return pSrc;
85271 }
85272 pSrc = pNew;
85273 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85274 pSrc->nAlloc = (u8)nGot;
85275 }
85276
85277 /* Move existing slots that come after the newly inserted slots
85278 ** out of the way */
85279 for(i=pSrc->nSrc-1; i>=iStart; i--){
85280 pSrc->a[i+nExtra] = pSrc->a[i];
85281 }
85282 pSrc->nSrc += (i8)nExtra;
85283
85284 /* Zero the newly allocated slots */
85285 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85286 for(i=iStart; i<iStart+nExtra; i++){
85287 pSrc->a[i].iCursor = -1;
@@ -87378,11 +87284,11 @@
87284 ** of x. If x is text, then we actually count UTF-8 characters.
87285 ** If x is a blob, then we count bytes.
87286 **
87287 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87288 **
87289 ** If p2 is negative, return the p2 characters preceding p1.
87290 */
87291 static void substrFunc(
87292 sqlite3_context *context,
87293 int argc,
87294 sqlite3_value **argv
@@ -88037,14 +87943,10 @@
87943 '0', '1', '2', '3', '4', '5', '6', '7',
87944 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
87945 };
87946
87947 /*
 
 
 
 
87948 ** Implementation of the QUOTE() function. This function takes a single
87949 ** argument. If the argument is numeric, the return value is the same as
87950 ** the argument. If the argument is NULL, the return value is the string
87951 ** "NULL". Otherwise, the argument is enclosed in single quotes with
87952 ** single-quote escapes.
@@ -88229,11 +88131,11 @@
88131 }
88132
88133 /*
88134 ** The replace() function. Three arguments are all strings: call
88135 ** them A, B, and C. The result is also a string which is derived
88136 ** from A by replacing every occurrence of B with C. The match
88137 ** must be exact. Collating sequences are not used.
88138 */
88139 static void replaceFunc(
88140 sqlite3_context *context,
88141 int argc,
@@ -94147,15 +94049,19 @@
94049 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
94050 }
94051 }
94052 }
94053 sz = -1;
94054 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
94055 #if SQLITE_MAX_MMAP_SIZE==0
94056 sz = 0;
94057 #endif
94058 if( rc==SQLITE_OK ){
94059 returnSingleInt(pParse, "mmap_size", sz);
94060 }else if( rc!=SQLITE_NOTFOUND ){
94061 pParse->nErr++;
94062 pParse->rc = rc;
94063 }
94064 }else
94065
94066 /*
94067 ** PRAGMA temp_store
@@ -94682,11 +94588,11 @@
94588 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94589 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94590 #endif
94591
94592 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
94593 /* Pragma "quick_check" is reduced version of
94594 ** integrity_check designed to detect most database corruption
94595 ** without most of the overhead of a full integrity-check.
94596 */
94597 if( sqlite3StrICmp(zLeft, "integrity_check")==0
94598 || sqlite3StrICmp(zLeft, "quick_check")==0
@@ -95140,14 +95046,14 @@
95046 }else
95047 #endif
95048
95049 #ifdef SQLITE_HAS_CODEC
95050 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95051 sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
95052 }else
95053 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95054 sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
95055 }else
95056 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95057 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95058 int i, h1, h2;
95059 char zKey[40];
@@ -95155,13 +95061,13 @@
95061 h1 += 9*(1&(h1>>6));
95062 h2 += 9*(1&(h2>>6));
95063 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95064 }
95065 if( (zLeft[3] & 0xf)==0xb ){
95066 sqlite3_key_v2(db, zDb, zKey, i/2);
95067 }else{
95068 sqlite3_rekey_v2(db, zDb, zKey, i/2);
95069 }
95070 }else
95071 #endif
95072 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95073 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
@@ -95792,11 +95698,11 @@
95698 }
95699
95700 sqlite3VtabUnlockList(db);
95701
95702 pParse->db = db;
95703 pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
95704 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95705 char *zSqlCopy;
95706 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95707 testcase( nBytes==mxLen );
95708 testcase( nBytes==mxLen+1 );
@@ -95814,11 +95720,11 @@
95720 pParse->zTail = &zSql[nBytes];
95721 }
95722 }else{
95723 sqlite3RunParser(pParse, zSql, &zErrMsg);
95724 }
95725 assert( 0==pParse->nQueryLoop );
95726
95727 if( db->mallocFailed ){
95728 pParse->rc = SQLITE_NOMEM;
95729 }
95730 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
@@ -96178,11 +96084,11 @@
96084 sqlite3DbFree(db, p);
96085 }
96086 }
96087
96088 /*
96089 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
96090 ** type of join. Return an integer constant that expresses that type
96091 ** in terms of the following bit values:
96092 **
96093 ** JT_INNER
96094 ** JT_CROSS
@@ -97592,11 +97498,11 @@
97498 int addr1, n;
97499 if( p->iLimit ) return;
97500
97501 /*
97502 ** "LIMIT -1" always shows all rows. There is some
97503 ** controversy about what the correct behavior should be.
97504 ** The current implementation interprets "LIMIT 0" to mean
97505 ** no rows.
97506 */
97507 sqlite3ExprCacheClear(pParse);
97508 assert( p->pOffset==0 || p->pLimit!=0 );
@@ -97607,12 +97513,12 @@
97513 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97514 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97515 VdbeComment((v, "LIMIT counter"));
97516 if( n==0 ){
97517 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97518 }else if( n>=0 && p->nSelectRow>(u64)n ){
97519 p->nSelectRow = n;
97520 }
97521 }else{
97522 sqlite3ExprCode(pParse, p->pLimit, iLimit);
97523 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97524 VdbeComment((v, "LIMIT counter"));
@@ -97802,13 +97708,13 @@
97708 pDelete = p->pPrior;
97709 p->pPrior = pPrior;
97710 p->nSelectRow += pPrior->nSelectRow;
97711 if( pPrior->pLimit
97712 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97713 && nLimit>0 && p->nSelectRow > (u64)nLimit
97714 ){
97715 p->nSelectRow = nLimit;
97716 }
97717 if( addr ){
97718 sqlite3VdbeJumpHere(v, addr);
97719 }
97720 break;
@@ -99953,15 +99859,14 @@
99859 Parse *pParse, /* Parse context */
99860 Table *pTab, /* Table being queried */
99861 Index *pIdx /* Index used to optimize scan, or NULL */
99862 ){
99863 if( pParse->explain==2 ){
99864 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
99865 pTab->zName,
99866 pIdx ? " USING COVERING INDEX " : "",
99867 pIdx ? pIdx->zName : ""
 
99868 );
99869 sqlite3VdbeAddOp4(
99870 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99871 );
99872 }
@@ -100115,11 +100020,11 @@
100020 }
100021 continue;
100022 }
100023
100024 /* Increment Parse.nHeight by the height of the largest expression
100025 ** tree referred to by this, the parent select. The child select
100026 ** may contain expression trees of at most
100027 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100028 ** more conservative than necessary, but much easier than enforcing
100029 ** an exact limit.
100030 */
@@ -100308,11 +100213,11 @@
100213 }
100214
100215 /* Set the limiter.
100216 */
100217 iEnd = sqlite3VdbeMakeLabel(v);
100218 p->nSelectRow = LARGEST_INT64;
100219 computeLimitRegisters(pParse, p, iEnd);
100220 if( p->iLimit==0 && addrSortIndex>=0 ){
100221 sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100222 p->selFlags |= SF_UseSorter;
100223 }
@@ -100336,13 +100241,17 @@
100241 ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100242
100243 /* Begin the database scan. */
100244 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100245 if( pWInfo==0 ) goto select_end;
100246 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
100247 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
100248 }
100249 if( sqlite3WhereIsDistinct(pWInfo) ){
100250 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
100251 }
100252 if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
100253
100254 /* If sorting index that was created by a prior OP_OpenEphemeral
100255 ** instruction ended up not being needed, then change the OP_OpenEphemeral
100256 ** into an OP_Noop.
100257 */
@@ -100351,11 +100260,12 @@
100260 p->addrOpenEphm[2] = -1;
100261 }
100262
100263 /* Use the standard inner loop. */
100264 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100265 sqlite3WhereContinueLabel(pWInfo),
100266 sqlite3WhereBreakLabel(pWInfo));
100267
100268 /* End the database scan loop.
100269 */
100270 sqlite3WhereEnd(pWInfo);
100271 }else{
@@ -100384,13 +100294,13 @@
100294 pItem->iAlias = 0;
100295 }
100296 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100297 pItem->iAlias = 0;
100298 }
100299 if( p->nSelectRow>100 ) p->nSelectRow = 100;
100300 }else{
100301 p->nSelectRow = 1;
100302 }
100303
100304
100305 /* Create a label to jump to when we want to abort the query */
100306 addrEnd = sqlite3VdbeMakeLabel(v);
@@ -100466,13 +100376,14 @@
100376 ** This might involve two separate loops with an OP_Sort in between, or
100377 ** it might be a single loop that uses an index to extract information
100378 ** in the right order to begin with.
100379 */
100380 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100381 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
100382 WHERE_GROUPBY, 0);
100383 if( pWInfo==0 ) goto select_end;
100384 if( sqlite3WhereIsOrdered(pWInfo) ){
100385 /* The optimizer is able to deliver rows in group by order so
100386 ** we do not have to sort. The OP_OpenEphemeral table will be
100387 ** cancelled later because we still need to use the pKeyInfo
100388 */
100389 groupBySort = 0;
@@ -100749,12 +100660,12 @@
100660 sqlite3ExprListDelete(db, pDel);
100661 goto select_end;
100662 }
100663 updateAccumulator(pParse, &sAggInfo);
100664 assert( pMinMax==0 || pMinMax->nExpr==1 );
100665 if( sqlite3WhereIsOrdered(pWInfo) ){
100666 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
100667 VdbeComment((v, "%s() by index",
100668 (flag==WHERE_ORDERBY_MIN?"min":"max")));
100669 }
100670 sqlite3WhereEnd(pWInfo);
100671 finalizeAggFunctions(pParse, &sAggInfo);
@@ -102109,11 +102020,11 @@
102020 }
102021
102022 /*
102023 ** This is called to code the required FOR EACH ROW triggers for an operation
102024 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102025 ** is given by the op parameter. The tr_tm parameter determines whether the
102026 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102027 ** parameter pChanges is passed the list of columns being modified.
102028 **
102029 ** If there are no triggers that fire at the specified time for the specified
102030 ** operation on pTab, this function is a no-op.
@@ -102560,11 +102471,11 @@
102471 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102472 pWInfo = sqlite3WhereBegin(
102473 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102474 );
102475 if( pWInfo==0 ) goto update_cleanup;
102476 okOnePass = sqlite3WhereOkOnePass(pWInfo);
102477
102478 /* Remember the rowid of every item to be updated.
102479 */
102480 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102481 if( !okOnePass ){
@@ -104397,22 +104308,165 @@
104308 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104309 /***/ int sqlite3WhereTrace = 0;
104310 #endif
104311 #if defined(SQLITE_DEBUG) \
104312 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104313 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
104314 # define WHERETRACE_ENABLED 1
104315 #else
104316 # define WHERETRACE(K,X)
104317 #endif
104318
104319 /* Forward reference
104320 */
104321 typedef struct WhereClause WhereClause;
104322 typedef struct WhereMaskSet WhereMaskSet;
104323 typedef struct WhereOrInfo WhereOrInfo;
104324 typedef struct WhereAndInfo WhereAndInfo;
104325 typedef struct WhereLevel WhereLevel;
104326 typedef struct WhereLoop WhereLoop;
104327 typedef struct WherePath WherePath;
104328 typedef struct WhereTerm WhereTerm;
104329 typedef struct WhereLoopBuilder WhereLoopBuilder;
104330 typedef struct WhereScan WhereScan;
104331
104332 /*
104333 ** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
104334 ** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
104335 ** (Virtual tables can return a larger cost, but let's assume they do not.)
104336 ** So all costs can be stored in a 16-bit unsigned integer without risk
104337 ** of overflow.
104338 **
104339 ** Costs are estimates, so don't go to the computational trouble to compute
104340 ** 10*log2(X) exactly. Instead, a close estimate is used. Any value of
104341 ** X<=1 is stored as 0. X=2 is 10. X=3 is 16. X=1000 is 99. etc.
104342 **
104343 ** The tool/wherecosttest.c source file implements a command-line program
104344 ** that will convert between WhereCost to integers and do addition and
104345 ** multiplication on WhereCost values. That command-line program is a
104346 ** useful utility to have around when working with this module.
104347 */
104348 typedef unsigned short int WhereCost;
104349
104350 /*
104351 ** This object contains information needed to implement a single nested
104352 ** loop in WHERE clause.
104353 **
104354 ** Contrast this object with WhereLoop. This object describes the
104355 ** implementation of the loop. WhereLoop describes the algorithm.
104356 ** This object contains a pointer to the WhereLoop algorithm as one of
104357 ** its elements.
104358 **
104359 ** The WhereInfo object contains a single instance of this object for
104360 ** each term in the FROM clause (which is to say, for each of the
104361 ** nested loops as implemented). The order of WhereLevel objects determines
104362 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
104363 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
104364 */
104365 struct WhereLevel {
104366 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
104367 int iTabCur; /* The VDBE cursor used to access the table */
104368 int iIdxCur; /* The VDBE cursor used to access pIdx */
104369 int addrBrk; /* Jump here to break out of the loop */
104370 int addrNxt; /* Jump here to start the next IN combination */
104371 int addrCont; /* Jump here to continue with the next loop cycle */
104372 int addrFirst; /* First instruction of interior of the loop */
104373 u8 iFrom; /* Which entry in the FROM clause */
104374 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
104375 int p1, p2; /* Operands of the opcode used to ends the loop */
104376 union { /* Information that depends on pWLoop->wsFlags */
104377 struct {
104378 int nIn; /* Number of entries in aInLoop[] */
104379 struct InLoop {
104380 int iCur; /* The VDBE cursor used by this IN operator */
104381 int addrInTop; /* Top of the IN loop */
104382 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
104383 } *aInLoop; /* Information about each nested IN operator */
104384 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
104385 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
104386 } u;
104387 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
104388 };
104389
104390 /*
104391 ** Each instance of this object represents an algorithm for evaluating one
104392 ** term of a join. Every term of the FROM clause will have at least
104393 ** one corresponding WhereLoop object (unless INDEXED BY constraints
104394 ** prevent a query solution - which is an error) and many terms of the
104395 ** FROM clause will have multiple WhereLoop objects, each describing a
104396 ** potential way of implementing that FROM-clause term, together with
104397 ** dependencies and cost estimates for using the chosen algorithm.
104398 **
104399 ** Query planning consists of building up a collection of these WhereLoop
104400 ** objects, then computing a particular sequence of WhereLoop objects, with
104401 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
104402 ** and that minimize the overall cost.
104403 */
104404 struct WhereLoop {
104405 Bitmask prereq; /* Bitmask of other loops that must run first */
104406 Bitmask maskSelf; /* Bitmask identifying table iTab */
104407 #ifdef SQLITE_DEBUG
104408 char cId; /* Symbolic ID of this loop for debugging use */
104409 #endif
104410 u8 iTab; /* Position in FROM clause of table for this loop */
104411 u8 iSortIdx; /* Sorting index number. 0==None */
104412 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
104413 WhereCost rRun; /* Cost of running each loop */
104414 WhereCost nOut; /* Estimated number of output rows */
104415 union {
104416 struct { /* Information for internal btree tables */
104417 int nEq; /* Number of equality constraints */
104418 Index *pIndex; /* Index used, or NULL */
104419 } btree;
104420 struct { /* Information for virtual tables */
104421 int idxNum; /* Index number */
104422 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
104423 u8 isOrdered; /* True if satisfies ORDER BY */
104424 u16 omitMask; /* Terms that may be omitted */
104425 char *idxStr; /* Index identifier string */
104426 } vtab;
104427 } u;
104428 u32 wsFlags; /* WHERE_* flags describing the plan */
104429 u16 nLTerm; /* Number of entries in aLTerm[] */
104430 /**** whereLoopXfer() copies fields above ***********************/
104431 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
104432 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
104433 WhereTerm **aLTerm; /* WhereTerms used */
104434 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
104435 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
104436 };
104437
104438 /* Forward declaration of methods */
104439 static int whereLoopResize(sqlite3*, WhereLoop*, int);
104440
104441 /*
104442 ** Each instance of this object holds a sequence of WhereLoop objects
104443 ** that implement some or all of a query plan.
104444 **
104445 ** Think of each WhereLoop objects as a node in a graph, which arcs
104446 ** showing dependences and costs for travelling between nodes. (That is
104447 ** not a completely accurate description because WhereLoop costs are a
104448 ** vector, not a scalar, and because dependences are many-to-one, not
104449 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
104450 ** Then a WherePath object is a path through the graph that visits some
104451 ** or all of the WhereLoop objects once.
104452 **
104453 ** The "solver" works by creating the N best WherePath objects of length
104454 ** 1. Then using those as a basis to compute the N best WherePath objects
104455 ** of length 2. And so forth until the length of WherePaths equals the
104456 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
104457 ** at the end is the choosen query plan.
104458 */
104459 struct WherePath {
104460 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
104461 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
104462 WhereCost nRow; /* Estimated number of rows generated by this path */
104463 WhereCost rCost; /* Total cost of this path */
104464 u8 isOrdered; /* True if this path satisfies ORDER BY */
104465 u8 isOrderedValid; /* True if the isOrdered field is valid */
104466 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
104467 };
104468
104469 /*
104470 ** The query generator uses an array of instances of this structure to
104471 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
104472 ** clause subexpression is separated from the others by AND operators,
@@ -104461,11 +104515,10 @@
104515 **
104516 ** The number of terms in a join is limited by the number of bits
104517 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
104518 ** is only able to process joins with 64 or fewer tables.
104519 */
 
104520 struct WhereTerm {
104521 Expr *pExpr; /* Pointer to the subexpression that is this term */
104522 int iParent; /* Disable pWC->a[iParent] when this term disabled */
104523 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
104524 union {
@@ -104495,10 +104548,26 @@
104548 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
104549 #else
104550 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
104551 #endif
104552
104553 /*
104554 ** An instance of the WhereScan object is used as an iterator for locating
104555 ** terms in the WHERE clause that are useful to the query planner.
104556 */
104557 struct WhereScan {
104558 WhereClause *pOrigWC; /* Original, innermost WhereClause */
104559 WhereClause *pWC; /* WhereClause currently being scanned */
104560 char *zCollName; /* Required collating sequence, if not NULL */
104561 char idxaff; /* Must match this affinity, if zCollName!=NULL */
104562 unsigned char nEquiv; /* Number of entries in aEquiv[] */
104563 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
104564 u32 opMask; /* Acceptable operators */
104565 int k; /* Resume scanning at this->pWC->a[this->k] */
104566 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
104567 };
104568
104569 /*
104570 ** An instance of the following structure holds all information about a
104571 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
104572 **
104573 ** Explanation of pOuter: For a WHERE clause of the form
@@ -104508,15 +104577,13 @@
104577 ** There are separate WhereClause objects for the whole clause and for
104578 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
104579 ** subclauses points to the WhereClause object for the whole clause.
104580 */
104581 struct WhereClause {
104582 WhereInfo *pWInfo; /* WHERE clause processing context */
 
104583 WhereClause *pOuter; /* Outer conjunction */
104584 u8 op; /* Split operator. TK_AND or TK_OR */
 
104585 int nTerm; /* Number of terms */
104586 int nSlot; /* Number of entries in a[] */
104587 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
104588 #if defined(SQLITE_SMALL_STACK)
104589 WhereTerm aStatic[1]; /* Initial static space for a[] */
@@ -104572,23 +104639,59 @@
104639 int n; /* Number of assigned cursor values */
104640 int ix[BMS]; /* Cursor assigned to each bit */
104641 };
104642
104643 /*
104644 ** This object is a convenience wrapper holding all information needed
104645 ** to construct WhereLoop objects for a particular query.
104646 */
104647 struct WhereLoopBuilder {
104648 WhereInfo *pWInfo; /* Information about this WHERE */
104649 WhereClause *pWC; /* WHERE clause terms */
104650 ExprList *pOrderBy; /* ORDER BY clause */
104651 WhereLoop *pNew; /* Template WhereLoop */
104652 WhereLoop *pBest; /* If non-NULL, store single best loop here */
104653 };
104654
104655 /*
104656 ** The WHERE clause processing routine has two halves. The
104657 ** first part does the start of the WHERE loop and the second
104658 ** half does the tail of the WHERE loop. An instance of
104659 ** this structure is returned by the first half and passed
104660 ** into the second half to give some continuity.
104661 **
104662 ** An instance of this object holds the complete state of the query
104663 ** planner.
104664 */
104665 struct WhereInfo {
104666 Parse *pParse; /* Parsing and code generating context */
104667 SrcList *pTabList; /* List of tables in the join */
104668 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
104669 ExprList *pDistinct; /* DISTINCT ON values, or NULL */
104670 WhereLoop *pLoops; /* List of all WhereLoop objects */
104671 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
104672 WhereCost nRowOut; /* Estimated number of output rows */
104673 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
104674 u8 bOBSat; /* ORDER BY satisfied by indices */
104675 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
104676 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
104677 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
104678 int iTop; /* The very beginning of the WHERE loop */
104679 int iContinue; /* Jump here to continue with next record */
104680 int iBreak; /* Jump here to break out of the loop */
104681 int nLevel; /* Number of nested loop */
104682 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
104683 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
104684 WhereClause sWC; /* Decomposition of the WHERE clause */
104685 WhereLevel a[1]; /* Information about each nest loop in WHERE */
104686 };
104687
104688 /*
104689 ** Bitmasks for the operators on WhereTerm objects. These are all
104690 ** operators that are of interest to the query planner. An
104691 ** OR-ed combination of these values can be used when searching for
104692 ** particular WhereTerms within a WhereClause.
104693 */
104694 #define WO_IN 0x001
104695 #define WO_EQ 0x002
104696 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
104697 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -104603,96 +104706,106 @@
104706
104707 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
104708 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
104709
104710 /*
104711 ** These are definitions of bits in the WhereLoop.wsFlags field.
104712 ** The particular combination of bits in each WhereLoop help to
104713 ** determine the algorithm that WhereLoop represents.
104714 */
104715 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR or x IN (...) or x IS NULL */
104716 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
104717 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
104718 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
104719 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
104720 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
104721 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
104722 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
104723 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
104724 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
104725 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
104726 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
104727 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
104728 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
104729 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
104730 #define WHERE_TEMP_INDEX 0x00004000 /* Uses an ephemeral index */
104731
104732
104733 /* Convert a WhereCost value (10 times log2(X)) into its integer value X.
104734 ** A rough approximation is used. The value returned is not exact.
104735 */
104736 static u64 whereCostToInt(WhereCost x){
104737 u64 n;
104738 if( x<10 ) return 1;
104739 n = x%10;
104740 x /= 10;
104741 if( n>=5 ) n -= 2;
104742 else if( n>=1 ) n -= 1;
104743 if( x>=3 ) return (n+8)<<(x-3);
104744 return (n+8)>>(3-x);
104745 }
104746
104747 /*
104748 ** Return the estimated number of output rows from a WHERE clause
104749 */
104750 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
104751 return whereCostToInt(pWInfo->nRowOut);
104752 }
104753
104754 /*
104755 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
104756 ** WHERE clause returns outputs for DISTINCT processing.
104757 */
104758 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
104759 return pWInfo->eDistinct;
104760 }
104761
104762 /*
104763 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
104764 ** Return FALSE if the output needs to be sorted.
104765 */
104766 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
104767 return pWInfo->bOBSat!=0;
104768 }
104769
104770 /*
104771 ** Return the VDBE address or label to jump to in order to continue
104772 ** immediately with the next row of a WHERE clause.
104773 */
104774 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
104775 return pWInfo->iContinue;
104776 }
104777
104778 /*
104779 ** Return the VDBE address or label to jump to in order to break
104780 ** out of a WHERE loop.
104781 */
104782 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
104783 return pWInfo->iBreak;
104784 }
104785
104786 /*
104787 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
104788 ** the rowids returned by a WHERE clause. Return FALSE if doing an
104789 ** UPDATE or DELETE might change subsequent WHERE clause results.
104790 */
104791 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
104792 return pWInfo->okOnePass;
104793 }
104794
104795 /*
104796 ** Initialize a preallocated WhereClause structure.
104797 */
104798 static void whereClauseInit(
104799 WhereClause *pWC, /* The WhereClause to be initialized */
104800 WhereInfo *pWInfo /* The WHERE processing context */
 
 
104801 ){
104802 pWC->pWInfo = pWInfo;
 
104803 pWC->pOuter = 0;
104804 pWC->nTerm = 0;
104805 pWC->nSlot = ArraySize(pWC->aStatic);
104806 pWC->a = pWC->aStatic;
 
104807 }
104808
104809 /* Forward reference */
104810 static void whereClauseClear(WhereClause*);
104811
@@ -104717,11 +104830,11 @@
104830 ** itself is not freed. This routine is the inverse of whereClauseInit().
104831 */
104832 static void whereClauseClear(WhereClause *pWC){
104833 int i;
104834 WhereTerm *a;
104835 sqlite3 *db = pWC->pWInfo->pParse->db;
104836 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104837 if( a->wtFlags & TERM_DYNAMIC ){
104838 sqlite3ExprDelete(db, a->pExpr);
104839 }
104840 if( a->wtFlags & TERM_ORINFO ){
@@ -104758,11 +104871,11 @@
104871 WhereTerm *pTerm;
104872 int idx;
104873 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
104874 if( pWC->nTerm>=pWC->nSlot ){
104875 WhereTerm *pOld = pWC->a;
104876 sqlite3 *db = pWC->pWInfo->pParse->db;
104877 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104878 if( pWC->a==0 ){
104879 if( wtFlags & TERM_DYNAMIC ){
104880 sqlite3ExprDelete(db, p);
104881 }
@@ -104798,12 +104911,12 @@
104911 **
104912 ** In the previous sentence and in the diagram, "slot[]" refers to
104913 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
104914 ** all terms of the WHERE clause.
104915 */
104916 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
104917 pWC->op = op;
104918 if( pExpr==0 ) return;
104919 if( pExpr->op!=op ){
104920 whereClauseInsert(pWC, pExpr, 0);
104921 }else{
104922 whereSplit(pWC, pExpr->pLeft, op);
@@ -104810,13 +104923,13 @@
104923 whereSplit(pWC, pExpr->pRight, op);
104924 }
104925 }
104926
104927 /*
104928 ** Initialize a WhereMaskSet object
104929 */
104930 #define initMaskSet(P) (P)->n=0
104931
104932 /*
104933 ** Return the bitmask for the given cursor number. Return 0 if
104934 ** iCursor is not in the set.
104935 */
@@ -104823,11 +104936,11 @@
104936 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104937 int i;
104938 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104939 for(i=0; i<pMaskSet->n; i++){
104940 if( pMaskSet->ix[i]==iCursor ){
104941 return MASKBIT(i);
104942 }
104943 }
104944 return 0;
104945 }
104946
@@ -104843,22 +104956,13 @@
104956 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104957 pMaskSet->ix[pMaskSet->n++] = iCursor;
104958 }
104959
104960 /*
104961 ** These routine walk (recursively) an expression tree and generates
104962 ** a bitmask indicating which tables are used in that expression
104963 ** tree.
 
 
 
 
 
 
 
 
 
104964 */
104965 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104966 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104967 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104968 Bitmask mask = 0;
@@ -104908,11 +105012,11 @@
105012 }
105013
105014 /*
105015 ** Return TRUE if the given operator is one of the operators that is
105016 ** allowed for an indexable WHERE clause term. The allowed operators are
105017 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
105018 **
105019 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
105020 ** of one of the following forms: column = expression column > expression
105021 ** column >= expression column < expression column <= expression
105022 ** expression = column expression > column expression >= column
@@ -104935,14 +105039,13 @@
105039 /*
105040 ** Commute a comparison operator. Expressions of the form "X op Y"
105041 ** are converted into "Y op X".
105042 **
105043 ** If left/right precedence rules come into play when determining the
105044 ** collating sequence, then COLLATE operators are adjusted to ensure
105045 ** that the collating sequence does not change. For example:
105046 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
 
105047 ** the left hand side of a comparison overrides any collation sequence
105048 ** attached to the right. For the same reason the EP_Collate flag
105049 ** is not commuted.
105050 */
105051 static void exprCommute(Parse *pParse, Expr *pExpr){
@@ -104994,10 +105097,134 @@
105097 assert( op!=TK_LE || c==WO_LE );
105098 assert( op!=TK_GT || c==WO_GT );
105099 assert( op!=TK_GE || c==WO_GE );
105100 return c;
105101 }
105102
105103 /*
105104 ** Advance to the next WhereTerm that matches according to the criteria
105105 ** established when the pScan object was initialized by whereScanInit().
105106 ** Return NULL if there are no more matching WhereTerms.
105107 */
105108 WhereTerm *whereScanNext(WhereScan *pScan){
105109 int iCur; /* The cursor on the LHS of the term */
105110 int iColumn; /* The column on the LHS of the term. -1 for IPK */
105111 Expr *pX; /* An expression being tested */
105112 WhereClause *pWC; /* Shorthand for pScan->pWC */
105113 WhereTerm *pTerm; /* The term being tested */
105114 int k = pScan->k; /* Where to start scanning */
105115
105116 while( pScan->iEquiv<=pScan->nEquiv ){
105117 iCur = pScan->aEquiv[pScan->iEquiv-2];
105118 iColumn = pScan->aEquiv[pScan->iEquiv-1];
105119 while( (pWC = pScan->pWC)!=0 ){
105120 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
105121 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
105122 if( (pTerm->eOperator & WO_EQUIV)!=0
105123 && pScan->nEquiv<ArraySize(pScan->aEquiv)
105124 ){
105125 int j;
105126 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105127 assert( pX->op==TK_COLUMN );
105128 for(j=0; j<pScan->nEquiv; j+=2){
105129 if( pScan->aEquiv[j]==pX->iTable
105130 && pScan->aEquiv[j+1]==pX->iColumn ){
105131 break;
105132 }
105133 }
105134 if( j==pScan->nEquiv ){
105135 pScan->aEquiv[j] = pX->iTable;
105136 pScan->aEquiv[j+1] = pX->iColumn;
105137 pScan->nEquiv += 2;
105138 }
105139 }
105140 if( (pTerm->eOperator & pScan->opMask)!=0 ){
105141 /* Verify the affinity and collating sequence match */
105142 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
105143 CollSeq *pColl;
105144 Parse *pParse = pWC->pWInfo->pParse;
105145 pX = pTerm->pExpr;
105146 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
105147 continue;
105148 }
105149 assert(pX->pLeft);
105150 pColl = sqlite3BinaryCompareCollSeq(pParse,
105151 pX->pLeft, pX->pRight);
105152 if( pColl==0 ) pColl = pParse->db->pDfltColl;
105153 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
105154 continue;
105155 }
105156 }
105157 if( (pTerm->eOperator & WO_EQ)!=0
105158 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
105159 && pX->iTable==pScan->aEquiv[0]
105160 && pX->iColumn==pScan->aEquiv[1]
105161 ){
105162 continue;
105163 }
105164 pScan->k = k+1;
105165 return pTerm;
105166 }
105167 }
105168 }
105169 pScan->pWC = pScan->pWC->pOuter;
105170 k = 0;
105171 }
105172 pScan->pWC = pScan->pOrigWC;
105173 k = 0;
105174 pScan->iEquiv += 2;
105175 }
105176 return 0;
105177 }
105178
105179 /*
105180 ** Initialize a WHERE clause scanner object. Return a pointer to the
105181 ** first match. Return NULL if there are no matches.
105182 **
105183 ** The scanner will be searching the WHERE clause pWC. It will look
105184 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
105185 ** iCur. The <op> must be one of the operators described by opMask.
105186 **
105187 ** If the search is for X and the WHERE clause contains terms of the
105188 ** form X=Y then this routine might also return terms of the form
105189 ** "Y <op> <expr>". The number of levels of transitivity is limited,
105190 ** but is enough to handle most commonly occurring SQL statements.
105191 **
105192 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
105193 ** index pIdx.
105194 */
105195 WhereTerm *whereScanInit(
105196 WhereScan *pScan, /* The WhereScan object being initialized */
105197 WhereClause *pWC, /* The WHERE clause to be scanned */
105198 int iCur, /* Cursor to scan for */
105199 int iColumn, /* Column to scan for */
105200 u32 opMask, /* Operator(s) to scan for */
105201 Index *pIdx /* Must be compatible with this index */
105202 ){
105203 int j;
105204
105205 /* memset(pScan, 0, sizeof(*pScan)); */
105206 pScan->pOrigWC = pWC;
105207 pScan->pWC = pWC;
105208 if( pIdx && iColumn>=0 ){
105209 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
105210 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
105211 if( NEVER(j>=pIdx->nColumn) ) return 0;
105212 }
105213 pScan->zCollName = pIdx->azColl[j];
105214 }else{
105215 pScan->idxaff = 0;
105216 pScan->zCollName = 0;
105217 }
105218 pScan->opMask = opMask;
105219 pScan->k = 0;
105220 pScan->aEquiv[0] = iCur;
105221 pScan->aEquiv[1] = iColumn;
105222 pScan->nEquiv = 2;
105223 pScan->iEquiv = 2;
105224 return whereScanNext(pScan);
105225 }
105226
105227 /*
105228 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105229 ** where X is a reference to the iColumn of table iCur and <op> is one of
105230 ** the WO_xx operator codes specified by the op parameter.
@@ -105026,98 +105253,32 @@
105253 int iColumn, /* Column number of LHS */
105254 Bitmask notReady, /* RHS must not overlap with this mask */
105255 u32 op, /* Mask of WO_xx values describing operator */
105256 Index *pIdx /* Must be compatible with this index, if not NULL */
105257 ){
105258 WhereTerm *pResult = 0;
105259 WhereTerm *p;
105260 WhereScan scan;
105261
105262 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
105263 while( p ){
105264 if( (p->prereqRight & notReady)==0 ){
105265 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
105266 return p;
105267 }
105268 if( pResult==0 ) pResult = p;
105269 }
105270 p = whereScanNext(&scan);
105271 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105272 return pResult;
105273 }
105274
105275 /* Forward reference */
105276 static void exprAnalyze(SrcList*, WhereClause*, int);
105277
105278 /*
105279 ** Call exprAnalyze on all terms in a WHERE clause.
 
 
105280 */
105281 static void exprAnalyzeAll(
105282 SrcList *pTabList, /* the FROM clause */
105283 WhereClause *pWC /* the WHERE clause to be analyzed */
105284 ){
@@ -105345,15 +105506,15 @@
105506 static void exprAnalyzeOrTerm(
105507 SrcList *pSrc, /* the FROM clause */
105508 WhereClause *pWC, /* the complete WHERE clause */
105509 int idxTerm /* Index of the OR-term to be analyzed */
105510 ){
105511 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105512 Parse *pParse = pWInfo->pParse; /* Parser context */
105513 sqlite3 *db = pParse->db; /* Database connection */
105514 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
105515 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
 
105516 int i; /* Loop counters */
105517 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
105518 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
105519 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
105520 Bitmask chngToIN; /* Tables that might satisfy case 1 */
@@ -105368,11 +105529,11 @@
105529 assert( pExpr->op==TK_OR );
105530 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105531 if( pOrInfo==0 ) return;
105532 pTerm->wtFlags |= TERM_ORINFO;
105533 pOrWc = &pOrInfo->wc;
105534 whereClauseInit(pOrWc, pWInfo);
105535 whereSplit(pOrWc, pExpr, TK_OR);
105536 exprAnalyzeAll(pSrc, pOrWc);
105537 if( db->mallocFailed ) return;
105538 assert( pOrWc->nTerm>=2 );
105539
@@ -105394,20 +105555,20 @@
105555 Bitmask b = 0;
105556 pOrTerm->u.pAndInfo = pAndInfo;
105557 pOrTerm->wtFlags |= TERM_ANDINFO;
105558 pOrTerm->eOperator = WO_AND;
105559 pAndWC = &pAndInfo->wc;
105560 whereClauseInit(pAndWC, pWC->pWInfo);
105561 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105562 exprAnalyzeAll(pSrc, pAndWC);
105563 pAndWC->pOuter = pWC;
105564 testcase( db->mallocFailed );
105565 if( !db->mallocFailed ){
105566 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105567 assert( pAndTerm->pExpr );
105568 if( allowedOp(pAndTerm->pExpr->op) ){
105569 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
105570 }
105571 }
105572 }
105573 indexable &= b;
105574 }
@@ -105414,14 +105575,14 @@
105575 }else if( pOrTerm->wtFlags & TERM_COPIED ){
105576 /* Skip this term for now. We revisit it when we process the
105577 ** corresponding TERM_VIRTUAL term */
105578 }else{
105579 Bitmask b;
105580 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
105581 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105582 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105583 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
105584 }
105585 indexable &= b;
105586 if( (pOrTerm->eOperator & WO_EQ)==0 ){
105587 chngToIN = 0;
105588 }else{
@@ -105479,11 +105640,11 @@
105640 /* This is the 2-bit case and we are on the second iteration and
105641 ** current term is from the first iteration. So skip this term. */
105642 assert( j==1 );
105643 continue;
105644 }
105645 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
105646 /* This term must be of the form t1.a==t2.b where t2 is in the
105647 ** chngToIN set but t1 is not. This term will be either preceeded
105648 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
105649 ** and use its inversion. */
105650 testcase( pOrTerm->wtFlags & TERM_COPIED );
@@ -105498,11 +105659,11 @@
105659 if( i<0 ){
105660 /* No candidate table+column was found. This can only occur
105661 ** on the second iteration */
105662 assert( j==1 );
105663 assert( IsPowerOfTwo(chngToIN) );
105664 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
105665 break;
105666 }
105667 testcase( j==1 );
105668
105669 /* We have found a candidate table and column. Check to see if that
@@ -105547,11 +105708,11 @@
105708 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105709 assert( pOrTerm->eOperator & WO_EQ );
105710 assert( pOrTerm->leftCursor==iCursor );
105711 assert( pOrTerm->u.leftColumn==iColumn );
105712 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105713 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
105714 pLeft = pOrTerm->pExpr->pLeft;
105715 }
105716 assert( pLeft!=0 );
105717 pDup = sqlite3ExprDup(db, pLeft, 0);
105718 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
@@ -105596,10 +105757,11 @@
105757 static void exprAnalyze(
105758 SrcList *pSrc, /* the FROM clause */
105759 WhereClause *pWC, /* the WHERE clause */
105760 int idxTerm /* Index of the term to be analyzed */
105761 ){
105762 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105763 WhereTerm *pTerm; /* The term to be analyzed */
105764 WhereMaskSet *pMaskSet; /* Set of table index masks */
105765 Expr *pExpr; /* The expression to be analyzed */
105766 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
105767 Bitmask prereqAll; /* Prerequesites of pExpr */
@@ -105606,18 +105768,18 @@
105768 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
105769 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
105770 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
105771 int noCase = 0; /* LIKE/GLOB distinguishes case */
105772 int op; /* Top-level operator. pExpr->op */
105773 Parse *pParse = pWInfo->pParse; /* Parsing context */
105774 sqlite3 *db = pParse->db; /* Database connection */
105775
105776 if( db->mallocFailed ){
105777 return;
105778 }
105779 pTerm = &pWC->a[idxTerm];
105780 pMaskSet = &pWInfo->sMaskSet;
105781 pExpr = pTerm->pExpr;
105782 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105783 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105784 op = pExpr->op;
105785 if( op==TK_IN ){
@@ -105891,15 +106053,12 @@
106053 */
106054 pTerm->prereqRight |= extraRight;
106055 }
106056
106057 /*
106058 ** This function searches pList for a entry that matches the iCol-th column
106059 ** of index pIdx.
 
 
 
106060 **
106061 ** If such an expression is found, its index in pList->a[] is returned. If
106062 ** no expression is found, -1 is returned.
106063 */
106064 static int findIndexCol(
@@ -105925,82 +106084,23 @@
106084 }
106085 }
106086
106087 return -1;
106088 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106089
106090 /*
106091 ** Return true if the DISTINCT expression-list passed as the third argument
106092 ** is redundant.
106093 **
106094 ** A DISTINCT list is redundant if the database contains some subset of
106095 ** columns that are unique and non-null.
106096 */
106097 static int isDistinctRedundant(
106098 Parse *pParse, /* Parsing context */
106099 SrcList *pTabList, /* The FROM clause */
106100 WhereClause *pWC, /* The WHERE clause */
106101 ExprList *pDistinct /* The result set that needs to be DISTINCT */
106102 ){
106103 Table *pTab;
106104 Index *pIdx;
106105 int i;
106106 int iBase;
@@ -106051,35 +106151,90 @@
106151 }
106152 }
106153
106154 return 0;
106155 }
106156
106157 /*
106158 ** The (an approximate) sum of two WhereCosts. This computation is
106159 ** not a simple "+" operator because WhereCost is stored as a logarithmic
106160 ** value.
106161 **
106162 */
106163 static WhereCost whereCostAdd(WhereCost a, WhereCost b){
106164 static const unsigned char x[] = {
106165 10, 10, /* 0,1 */
106166 9, 9, /* 2,3 */
106167 8, 8, /* 4,5 */
106168 7, 7, 7, /* 6,7,8 */
106169 6, 6, 6, /* 9,10,11 */
106170 5, 5, 5, /* 12-14 */
106171 4, 4, 4, 4, /* 15-18 */
106172 3, 3, 3, 3, 3, 3, /* 19-24 */
106173 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
106174 };
106175 if( a>=b ){
106176 if( a>b+49 ) return a;
106177 if( a>b+31 ) return a+1;
106178 return a+x[a-b];
106179 }else{
106180 if( b>a+49 ) return b;
106181 if( b>a+31 ) return b+1;
106182 return b+x[b-a];
106183 }
106184 }
106185
106186 /*
106187 ** Convert an integer into a WhereCost. In other words, compute a
106188 ** good approximatation for 10*log2(x).
 
 
 
106189 */
106190 static WhereCost whereCost(tRowcnt x){
106191 static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
106192 WhereCost y = 40;
106193 if( x<8 ){
106194 if( x<2 ) return 0;
106195 while( x<8 ){ y -= 10; x <<= 1; }
106196 }else{
106197 while( x>255 ){ y += 40; x >>= 4; }
106198 while( x>15 ){ y += 10; x >>= 1; }
106199 }
106200 return a[x&7] + y - 10;
106201 }
106202
106203 #ifndef SQLITE_OMIT_VIRTUALTABLE
106204 /*
106205 ** Convert a double (as received from xBestIndex of a virtual table)
106206 ** into a WhereCost. In other words, compute an approximation for
106207 ** 10*log2(x).
106208 */
106209 static WhereCost whereCostFromDouble(double x){
106210 u64 a;
106211 WhereCost e;
106212 assert( sizeof(x)==8 && sizeof(a)==8 );
106213 if( x<=1 ) return 0;
106214 if( x<=2000000000 ) return whereCost((tRowcnt)x);
106215 memcpy(&a, &x, 8);
106216 e = (a>>52) - 1022;
106217 return e*10;
106218 }
106219 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106220
106221 /*
106222 ** Estimate the logarithm of the input value to base 2.
106223 */
106224 static WhereCost estLog(WhereCost N){
106225 WhereCost x = whereCost(N);
106226 return x>33 ? x - 33 : 0;
106227 }
106228
106229 /*
106230 ** Two routines for printing the content of an sqlite3_index_info
106231 ** structure. Used for testing and debugging only. If neither
106232 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106233 ** are no-ops.
106234 */
106235 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
106236 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106237 int i;
106238 if( !sqlite3WhereTrace ) return;
106239 for(i=0; i<p->nConstraint; i++){
106240 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
@@ -106113,111 +106268,10 @@
106268 #else
106269 #define TRACE_IDX_INPUTS(A)
106270 #define TRACE_IDX_OUTPUTS(A)
106271 #endif
106272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106273 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106274 /*
106275 ** Return TRUE if the WHERE clause term pTerm is of a form where it
106276 ** could be used with an index to access pSrc, assuming an appropriate
106277 ** index existed.
@@ -106229,92 +106283,17 @@
106283 ){
106284 char aff;
106285 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106286 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106287 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106288 if( pTerm->u.leftColumn<0 ) return 0;
106289 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106290 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106291 return 1;
106292 }
106293 #endif
106294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106295
106296 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106297 /*
106298 ** Generate code to construct the Index object for an automatic index
106299 ** and to set up the WhereLevel object pLevel so that the code generator
@@ -106340,10 +106319,11 @@
106319 int regRecord; /* Register holding an index record */
106320 int n; /* Column counter */
106321 int i; /* Loop counter */
106322 int mxBitCol; /* Maximum column in pSrc->colUsed */
106323 CollSeq *pColl; /* Collating sequence to on a column */
106324 WhereLoop *pLoop; /* The Loop object */
106325 Bitmask idxCols; /* Bitmap of columns used for indexing */
106326 Bitmask extraCols; /* Bitmap of additional columns */
106327
106328 /* Generate code to skip over the creation and initialization of the
106329 ** transient index on 2nd and subsequent iterations of the loop. */
@@ -106354,54 +106334,58 @@
106334 /* Count the number of columns that will be added to the index
106335 ** and used to match WHERE clause constraints */
106336 nColumn = 0;
106337 pTable = pSrc->pTab;
106338 pWCEnd = &pWC->a[pWC->nTerm];
106339 pLoop = pLevel->pWLoop;
106340 idxCols = 0;
106341 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106342 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106343 int iCol = pTerm->u.leftColumn;
106344 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106345 testcase( iCol==BMS );
106346 testcase( iCol==BMS-1 );
106347 if( (idxCols & cMask)==0 ){
106348 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
106349 pLoop->aLTerm[nColumn++] = pTerm;
106350 idxCols |= cMask;
106351 }
106352 }
106353 }
106354 assert( nColumn>0 );
106355 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
106356 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
106357 | WHERE_TEMP_INDEX;
106358
106359 /* Count the number of additional columns needed to create a
106360 ** covering index. A "covering index" is an index that contains all
106361 ** columns that are needed by the query. With a covering index, the
106362 ** original table never needs to be accessed. Automatic indices must
106363 ** be a covering index because the index will not be updated if the
106364 ** original table changes and the index and table cannot both be used
106365 ** if they go out of sync.
106366 */
106367 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
106368 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106369 testcase( pTable->nCol==BMS-1 );
106370 testcase( pTable->nCol==BMS-2 );
106371 for(i=0; i<mxBitCol; i++){
106372 if( extraCols & MASKBIT(i) ) nColumn++;
106373 }
106374 if( pSrc->colUsed & MASKBIT(BMS-1) ){
106375 nColumn += pTable->nCol - BMS + 1;
106376 }
106377 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
106378
106379 /* Construct the Index object to describe this index */
106380 nByte = sizeof(Index);
106381 nByte += nColumn*sizeof(int); /* Index.aiColumn */
106382 nByte += nColumn*sizeof(char*); /* Index.azColl */
106383 nByte += nColumn; /* Index.aSortOrder */
106384 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106385 if( pIdx==0 ) return;
106386 pLoop->u.btree.pIndex = pIdx;
106387 pIdx->azColl = (char**)&pIdx[1];
106388 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106389 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106390 pIdx->zName = "auto-index";
106391 pIdx->nColumn = nColumn;
@@ -106409,11 +106393,13 @@
106393 n = 0;
106394 idxCols = 0;
106395 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106396 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106397 int iCol = pTerm->u.leftColumn;
106398 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106399 testcase( iCol==BMS-1 );
106400 testcase( iCol==BMS );
106401 if( (idxCols & cMask)==0 ){
106402 Expr *pX = pTerm->pExpr;
106403 idxCols |= cMask;
106404 pIdx->aiColumn[n] = pTerm->u.leftColumn;
106405 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
@@ -106420,22 +106406,22 @@
106406 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106407 n++;
106408 }
106409 }
106410 }
106411 assert( (u32)n==pLoop->u.btree.nEq );
106412
106413 /* Add additional columns needed to make the automatic index into
106414 ** a covering index */
106415 for(i=0; i<mxBitCol; i++){
106416 if( extraCols & MASKBIT(i) ){
106417 pIdx->aiColumn[n] = i;
106418 pIdx->azColl[n] = "BINARY";
106419 n++;
106420 }
106421 }
106422 if( pSrc->colUsed & MASKBIT(BMS-1) ){
106423 for(i=BMS-1; i<pTable->nCol; i++){
106424 pIdx->aiColumn[n] = i;
106425 pIdx->azColl[n] = "BINARY";
106426 n++;
106427 }
@@ -106443,10 +106429,11 @@
106429 assert( n==nColumn );
106430
106431 /* Create the automatic index */
106432 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106433 assert( pLevel->iIdxCur>=0 );
106434 pLevel->iIdxCur = pParse->nTab++;
106435 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106436 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106437 VdbeComment((v, "for %s", pTable->zName));
106438
106439 /* Fill the automatic index with content */
@@ -106469,26 +106456,25 @@
106456 /*
106457 ** Allocate and populate an sqlite3_index_info structure. It is the
106458 ** responsibility of the caller to eventually release the structure
106459 ** by passing the pointer returned by this function to sqlite3_free().
106460 */
106461 static sqlite3_index_info *allocateIndexInfo(
106462 Parse *pParse,
106463 WhereClause *pWC,
106464 struct SrcList_item *pSrc,
106465 ExprList *pOrderBy
106466 ){
106467 int i, j;
106468 int nTerm;
106469 struct sqlite3_index_constraint *pIdxCons;
106470 struct sqlite3_index_orderby *pIdxOrderBy;
106471 struct sqlite3_index_constraint_usage *pUsage;
106472 WhereTerm *pTerm;
106473 int nOrderBy;
106474 sqlite3_index_info *pIdxInfo;
106475
 
 
106476 /* Count the number of possible WHERE clause constraints referring
106477 ** to this virtual table */
106478 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106479 if( pTerm->leftCursor != pSrc->iCursor ) continue;
106480 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
@@ -106520,11 +106506,10 @@
106506 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106507 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106508 + sizeof(*pIdxOrderBy)*nOrderBy );
106509 if( pIdxInfo==0 ){
106510 sqlite3ErrorMsg(pParse, "out of memory");
 
106511 return 0;
106512 }
106513
106514 /* Initialize the structure. The sqlite3_index_info structure contains
106515 ** many fields that are declared "const" to prevent xBestIndex from
@@ -106576,12 +106561,12 @@
106561 }
106562
106563 /*
106564 ** The table object reference passed as the second argument to this function
106565 ** must represent a virtual table. This function invokes the xBestIndex()
106566 ** method of the virtual table with the sqlite3_index_info object that
106567 ** comes in as the 3rd argument to this function.
106568 **
106569 ** If an error occurs, pParse is populated with an error message and a
106570 ** non-zero value is returned. Otherwise, 0 is returned and the output
106571 ** part of the sqlite3_index_info structure is left populated.
106572 **
@@ -106592,11 +106577,10 @@
106577 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106578 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106579 int i;
106580 int rc;
106581
 
106582 TRACE_IDX_INPUTS(p);
106583 rc = pVtab->pModule->xBestIndex(pVtab, p);
106584 TRACE_IDX_OUTPUTS(p);
106585
106586 if( rc!=SQLITE_OK ){
@@ -106618,211 +106602,12 @@
106602 }
106603 }
106604
106605 return pParse->nErr;
106606 }
106607 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
106608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106609
106610 #ifdef SQLITE_ENABLE_STAT3
106611 /*
106612 ** Estimate the location of a particular key among all keys in an
106613 ** index. Store the results in aStat as follows:
@@ -107060,11 +106845,11 @@
106845 Parse *pParse, /* Parsing & code generating context */
106846 Index *p, /* The index containing the range-compared column; "x" */
106847 int nEq, /* index into p->aCol[] of the range-compared column */
106848 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
106849 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
106850 WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
106851 ){
106852 int rc = SQLITE_OK;
106853
106854 #ifdef SQLITE_ENABLE_STAT3
106855
@@ -107098,29 +106883,35 @@
106883 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
106884 }
106885 sqlite3ValueFree(pRangeVal);
106886 }
106887 if( rc==SQLITE_OK ){
106888 WhereCost iBase = whereCost(p->aiRowEst[0]);
106889 if( iUpper>iLower ){
106890 iBase -= whereCost(iUpper - iLower);
 
106891 }
106892 *pRangeDiv = iBase;
106893 WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
106894 (u32)iLower, (u32)iUpper, *pRangeDiv));
106895 return SQLITE_OK;
106896 }
106897 }
106898 #else
106899 UNUSED_PARAMETER(pParse);
106900 UNUSED_PARAMETER(p);
106901 UNUSED_PARAMETER(nEq);
106902 #endif
106903 assert( pLower || pUpper );
106904 *pRangeDiv = 0;
106905 /* TUNING: Each inequality constraint reduces the search space 4-fold.
106906 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
106907 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
106908 *pRangeDiv += 20; assert( 20==whereCost(4) );
106909 }
106910 if( pUpper ){
106911 *pRangeDiv += 20; assert( 20==whereCost(4) );
106912 }
106913 return rc;
106914 }
106915
106916 #ifdef SQLITE_ENABLE_STAT3
106917 /*
@@ -107142,11 +106933,11 @@
106933 */
106934 static int whereEqualScanEst(
106935 Parse *pParse, /* Parsing & code generating context */
106936 Index *p, /* The index whose left-most column is pTerm */
106937 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
106938 tRowcnt *pnRow /* Write the revised row estimate here */
106939 ){
106940 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
106941 u8 aff; /* Column affinity */
106942 int rc; /* Subfunction return code */
106943 tRowcnt a[2]; /* Statistics */
@@ -107161,11 +106952,11 @@
106952 pRhs = sqlite3ValueNew(pParse->db);
106953 }
106954 if( pRhs==0 ) return SQLITE_NOTFOUND;
106955 rc = whereKeyStats(pParse, p, pRhs, 0, a);
106956 if( rc==SQLITE_OK ){
106957 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
106958 *pnRow = a[1];
106959 }
106960 whereEqualScanEst_cancel:
106961 sqlite3ValueFree(pRhs);
106962 return rc;
@@ -107191,16 +106982,16 @@
106982 */
106983 static int whereInScanEst(
106984 Parse *pParse, /* Parsing & code generating context */
106985 Index *p, /* The index whose left-most column is pTerm */
106986 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
106987 tRowcnt *pnRow /* Write the revised row estimate here */
106988 ){
106989 int rc = SQLITE_OK; /* Subfunction return code */
106990 tRowcnt nEst; /* Number of rows for a single term */
106991 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
106992 int i; /* Loop counter */
106993
106994 assert( p->aSample!=0 );
106995 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
106996 nEst = p->aiRowEst[0];
106997 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
@@ -107207,888 +106998,15 @@
106998 nRowEst += nEst;
106999 }
107000 if( rc==SQLITE_OK ){
107001 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107002 *pnRow = nRowEst;
107003 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
107004 }
107005 return rc;
107006 }
107007 #endif /* defined(SQLITE_ENABLE_STAT3) */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107008
107009 /*
107010 ** Disable a term in the WHERE clause. Except, do not disable the term
107011 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
107012 ** or USING clause of that join.
@@ -108183,10 +107101,11 @@
107101 static int codeEqualityTerm(
107102 Parse *pParse, /* The parsing context */
107103 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
107104 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
107105 int iEq, /* Index of the equality term within this level */
107106 int bRev, /* True for reverse-order IN operations */
107107 int iTarget /* Attempt to leave results in this register */
107108 ){
107109 Expr *pX = pTerm->pExpr;
107110 Vdbe *v = pParse->pVdbe;
107111 int iReg; /* Register holding results */
@@ -108200,18 +107119,17 @@
107119 #ifndef SQLITE_OMIT_SUBQUERY
107120 }else{
107121 int eType;
107122 int iTab;
107123 struct InLoop *pIn;
107124 WhereLoop *pLoop = pLevel->pWLoop;
107125
107126 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
107127 && pLoop->u.btree.pIndex!=0
107128 && pLoop->u.btree.pIndex->aSortOrder[iEq]
107129 ){
107130 testcase( iEq==0 );
 
 
107131 testcase( bRev );
107132 bRev = !bRev;
107133 }
107134 assert( pX->op==TK_IN );
107135 iReg = iTarget;
@@ -108220,11 +107138,12 @@
107138 testcase( bRev );
107139 bRev = !bRev;
107140 }
107141 iTab = pX->iTable;
107142 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
107143 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
107144 pLoop->wsFlags |= WHERE_IN_ABLE;
107145 if( pLevel->u.in.nIn==0 ){
107146 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107147 }
107148 pLevel->u.in.nIn++;
107149 pLevel->u.in.aInLoop =
@@ -108290,33 +107209,35 @@
107209 ** string in this example would be set to SQLITE_AFF_NONE.
107210 */
107211 static int codeAllEqualityTerms(
107212 Parse *pParse, /* Parsing context */
107213 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
107214 int bRev, /* Reverse the order of IN operators */
 
107215 int nExtraReg, /* Number of extra registers to allocate */
107216 char **pzAff /* OUT: Set to point to affinity string */
107217 ){
107218 int nEq; /* The number of == or IN constraints to code */
107219 Vdbe *v = pParse->pVdbe; /* The vm under construction */
107220 Index *pIdx; /* The index being used for this loop */
 
107221 WhereTerm *pTerm; /* A single constraint term */
107222 WhereLoop *pLoop; /* The WhereLoop object */
107223 int j; /* Loop counter */
107224 int regBase; /* Base register */
107225 int nReg; /* Number of registers to allocate */
107226 char *zAff; /* Affinity string to return */
107227
107228 /* This module is only called on query plans that use an index. */
107229 pLoop = pLevel->pWLoop;
107230 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
107231 nEq = pLoop->u.btree.nEq;
107232 pIdx = pLoop->u.btree.pIndex;
107233 assert( pIdx!=0 );
107234
107235 /* Figure out how many memory cells we will need then allocate them.
107236 */
107237 regBase = pParse->nMem + 1;
107238 nReg = pLoop->u.btree.nEq + nExtraReg;
107239 pParse->nMem += nReg;
107240
107241 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
107242 if( !zAff ){
107243 pParse->db->mallocFailed = 1;
@@ -108325,18 +107246,17 @@
107246 /* Evaluate the equality constraints
107247 */
107248 assert( pIdx->nColumn>=nEq );
107249 for(j=0; j<nEq; j++){
107250 int r1;
107251 pTerm = pLoop->aLTerm[j];
107252 assert( pTerm!=0 );
 
107253 /* The following true for indices with redundant columns.
107254 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
107255 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
107256 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107257 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
107258 if( r1!=regBase+j ){
107259 if( nReg==1 ){
107260 sqlite3ReleaseTempReg(pParse, regBase);
107261 regBase = r1;
107262 }else{
@@ -108400,20 +107320,19 @@
107320 **
107321 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
107322 ** It is the responsibility of the caller to free the buffer when it is
107323 ** no longer required.
107324 */
107325 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
107326 Index *pIndex = pLoop->u.btree.pIndex;
107327 int nEq = pLoop->u.btree.nEq;
 
107328 int i, j;
107329 Column *aCol = pTab->aCol;
107330 int *aiColumn = pIndex->aiColumn;
107331 StrAccum txt;
107332
107333 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
107334 return 0;
107335 }
107336 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
107337 txt.db = db;
107338 sqlite3StrAccumAppend(&txt, " (", 2);
@@ -108420,15 +107339,15 @@
107339 for(i=0; i<nEq; i++){
107340 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
107341 }
107342
107343 j = i;
107344 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
107345 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107346 explainAppendTerm(&txt, i++, z, ">");
107347 }
107348 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
107349 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107350 explainAppendTerm(&txt, i, z, "<");
107351 }
107352 sqlite3StrAccumAppend(&txt, ")", 1);
107353 return sqlite3StrAccumFinish(&txt);
@@ -108447,24 +107366,26 @@
107366 int iLevel, /* Value for "level" column of output */
107367 int iFrom, /* Value for "from" column of output */
107368 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
107369 ){
107370 if( pParse->explain==2 ){
 
107371 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
107372 Vdbe *v = pParse->pVdbe; /* VM being constructed */
107373 sqlite3 *db = pParse->db; /* Database handle */
107374 char *zMsg; /* Text to add to EQP output */
 
107375 int iId = pParse->iSelectId; /* Select id (left-most output column) */
107376 int isSearch; /* True for a SEARCH. False for SCAN. */
107377 WhereLoop *pLoop; /* The controlling WhereLoop object */
107378 u32 flags; /* Flags that describe this loop */
107379
107380 pLoop = pLevel->pWLoop;
107381 flags = pLoop->wsFlags;
107382 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
107383
107384 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107385 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
107386 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107387
107388 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
107389 if( pItem->pSelect ){
107390 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
107391 }else{
@@ -108472,47 +107393,42 @@
107393 }
107394
107395 if( pItem->zAlias ){
107396 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
107397 }
107398 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
107399 && ALWAYS(pLoop->u.btree.pIndex!=0)
107400 ){
107401 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
107402 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
107403 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
107404 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
107405 ((flags & WHERE_TEMP_INDEX)?"":" "),
107406 ((flags & WHERE_TEMP_INDEX)?"": pLoop->u.btree.pIndex->zName),
107407 zWhere
107408 );
107409 sqlite3DbFree(db, zWhere);
107410 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
107411 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
107412
107413 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
107414 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
107415 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
107416 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
107417 }else if( flags&WHERE_BTM_LIMIT ){
107418 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
107419 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
107420 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
107421 }
107422 }
107423 #ifndef SQLITE_OMIT_VIRTUALTABLE
107424 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
 
107425 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
107426 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
107427 }
107428 #endif
107429 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
 
 
 
 
 
 
107430 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
107431 }
107432 }
107433 #else
107434 # define explainOneScan(u,v,w,x,y,z)
@@ -108524,19 +107440,19 @@
107440 ** implementation described by pWInfo.
107441 */
107442 static Bitmask codeOneLoopStart(
107443 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
107444 int iLevel, /* Which level of pWInfo->a[] should be coded */
 
107445 Bitmask notReady /* Which tables are currently available */
107446 ){
107447 int j, k; /* Loop counters */
107448 int iCur; /* The VDBE cursor for the table */
107449 int addrNxt; /* Where to jump to continue with the next IN case */
107450 int omitTable; /* True if we use the index only */
107451 int bRev; /* True if we need to scan in reverse order */
107452 WhereLevel *pLevel; /* The where level to be coded */
107453 WhereLoop *pLoop; /* The WhereLoop object being coded */
107454 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
107455 WhereTerm *pTerm; /* A WHERE clause term */
107456 Parse *pParse; /* Parsing context */
107457 Vdbe *v; /* The prepared stmt under constructions */
107458 struct SrcList_item *pTabItem; /* FROM clause term being coded */
@@ -108546,17 +107462,18 @@
107462 int iReleaseReg = 0; /* Temp register to free before returning */
107463 Bitmask newNotReady; /* Return value */
107464
107465 pParse = pWInfo->pParse;
107466 v = pParse->pVdbe;
107467 pWC = &pWInfo->sWC;
107468 pLevel = &pWInfo->a[iLevel];
107469 pLoop = pLevel->pWLoop;
107470 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
107471 iCur = pTabItem->iCursor;
107472 bRev = (pWInfo->revMask>>iLevel)&1;
107473 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
107474 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
107475 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
107476
107477 /* Create labels for the "break" and "continue" instructions
107478 ** for the current loop. Jump to addrBrk to break out of a loop.
107479 ** Jump to cont to go immediately to the next iteration of the
@@ -108589,51 +107506,41 @@
107506 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
107507 pLevel->op = OP_Goto;
107508 }else
107509
107510 #ifndef SQLITE_OMIT_VIRTUALTABLE
107511 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107512 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
107513 ** to access the data.
107514 */
107515 int iReg; /* P3 Value for OP_VFilter */
107516 int addrNotFound;
107517 int nConstraint = pLoop->nLTerm;
 
 
 
 
 
107518
107519 sqlite3ExprCachePush(pParse);
107520 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
107521 addrNotFound = pLevel->addrBrk;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107522 for(j=0; j<nConstraint; j++){
107523 int iTarget = iReg+j+2;
107524 pTerm = pLoop->aLTerm[j];
107525 if( pTerm==0 ) continue;
107526 if( pTerm->eOperator & WO_IN ){
107527 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
107528 addrNotFound = pLevel->addrNxt;
107529 }else{
107530 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
107531 }
107532 }
107533 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
107534 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
107535 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
107536 pLoop->u.vtab.idxStr,
107537 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
107538 pLoop->u.vtab.needFree = 0;
107539 for(j=0; j<nConstraint && j<16; j++){
107540 if( (pLoop->u.vtab.omitMask>>j)&1 ){
107541 disableTerm(pLevel, pLoop->aLTerm[j]);
107542 }
107543 }
107544 pLevel->op = OP_VNext;
107545 pLevel->p1 = iCur;
107546 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
@@ -108640,41 +107547,49 @@
107547 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
107548 sqlite3ExprCachePop(pParse, 1);
107549 }else
107550 #endif /* SQLITE_OMIT_VIRTUALTABLE */
107551
107552 if( (pLoop->wsFlags & WHERE_IPK)!=0
107553 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
107554 ){
107555 /* Case 2: We can directly reference a single row using an
107556 ** equality comparison against the ROWID field. Or
107557 ** we reference multiple rows using a "rowid IN (...)"
107558 ** construct.
107559 */
107560 assert( pLoop->u.btree.nEq==1 );
107561 iReleaseReg = sqlite3GetTempReg(pParse);
107562 pTerm = pLoop->aLTerm[0];
107563 assert( pTerm!=0 );
107564 assert( pTerm->pExpr!=0 );
107565 assert( omitTable==0 );
107566 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107567 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
107568 addrNxt = pLevel->addrNxt;
107569 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
107570 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
107571 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
107572 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107573 VdbeComment((v, "pk"));
107574 pLevel->op = OP_Noop;
107575 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
107576 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
107577 ){
107578 /* Case 3: We have an inequality comparison against the ROWID field.
107579 */
107580 int testOp = OP_Noop;
107581 int start;
107582 int memEndValue = 0;
107583 WhereTerm *pStart, *pEnd;
107584
107585 assert( omitTable==0 );
107586 j = 0;
107587 pStart = pEnd = 0;
107588 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
107589 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
107590 assert( pStart!=0 || pEnd!=0 );
107591 if( bRev ){
107592 pTerm = pStart;
107593 pStart = pEnd;
107594 pEnd = pTerm;
107595 }
@@ -108725,24 +107640,20 @@
107640 }
107641 start = sqlite3VdbeCurrentAddr(v);
107642 pLevel->op = bRev ? OP_Prev : OP_Next;
107643 pLevel->p1 = iCur;
107644 pLevel->p2 = start;
107645 assert( pLevel->p5==0 );
 
 
 
 
107646 if( testOp!=OP_Noop ){
107647 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107648 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
107649 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107650 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
107651 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
107652 }
107653 }else if( pLoop->wsFlags & WHERE_INDEXED ){
107654 /* Case 4: A scan using an index.
107655 **
107656 ** The WHERE clause may contain zero or more equality
107657 ** terms ("==" or "IN" operators) that refer to the N
107658 ** left-most columns of the index. It may also contain
107659 ** inequality constraints (>, <, >= or <=) on the indexed
@@ -108784,12 +107695,12 @@
107695 static const u8 aEndOp[] = {
107696 OP_Noop, /* 0: (!end_constraints) */
107697 OP_IdxGE, /* 1: (end_constraints && !bRev) */
107698 OP_IdxLT /* 2: (end_constraints && bRev) */
107699 };
107700 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
107701 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
107702 int regBase; /* Base register holding constraint values */
107703 int r1; /* Temp register */
107704 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
107705 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
107706 int startEq; /* True if range start uses ==, >= or <= */
@@ -108801,24 +107712,23 @@
107712 int nExtraReg = 0; /* Number of extra registers needed */
107713 int op; /* Instruction opcode */
107714 char *zStartAff; /* Affinity for start of range constraint */
107715 char *zEndAff; /* Affinity for end of range constraint */
107716
107717 pIdx = pLoop->u.btree.pIndex;
107718 iIdxCur = pLevel->iIdxCur;
 
107719
107720 /* If this loop satisfies a sort order (pOrderBy) request that
107721 ** was passed to this function to implement a "SELECT min(x) ..."
107722 ** query, then the caller will only allow the loop to run for
107723 ** a single iteration. This means that the first row returned
107724 ** should not have a NULL value stored in 'x'. If column 'x' is
107725 ** the first one after the nEq equality constraints in the index,
107726 ** this requires some special handling.
107727 */
107728 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
107729 && (pWInfo->bOBSat!=0)
107730 && (pIdx->nColumn>nEq)
107731 ){
107732 /* assert( pOrderBy->nExpr==1 ); */
107733 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
107734 isMinQuery = 1;
@@ -108826,26 +107736,25 @@
107736 }
107737
107738 /* Find any inequality constraint terms for the start and end
107739 ** of the range.
107740 */
107741 j = nEq;
107742 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
107743 pRangeStart = pLoop->aLTerm[j++];
107744 nExtraReg = 1;
107745 }
107746 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
107747 pRangeEnd = pLoop->aLTerm[j++];
107748 nExtraReg = 1;
107749 }
107750
107751 /* Generate code to evaluate all constraint terms using == or IN
107752 ** and store the values of those terms in an array of registers
107753 ** starting at regBase.
107754 */
107755 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
 
 
107756 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
107757 addrNxt = pLevel->addrNxt;
107758
107759 /* If we are doing a reverse order scan on an ascending index, or
107760 ** a forward order scan on a descending index, interchange the
@@ -108855,14 +107764,14 @@
107764 || (bRev && pIdx->nColumn==nEq)
107765 ){
107766 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
107767 }
107768
107769 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
107770 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
107771 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
107772 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
107773 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
107774 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
107775 start_constraints = pRangeStart || nEq>0;
107776
107777 /* Seek the index cursor to the start of the range. */
@@ -108948,13 +107857,13 @@
107857 /* If there are inequality constraints, check that the value
107858 ** of the table column that the inequality contrains is not NULL.
107859 ** If it is, jump to the next iteration of the loop.
107860 */
107861 r1 = sqlite3GetTempReg(pParse);
107862 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
107863 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
107864 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
107865 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
107866 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
107867 }
107868 sqlite3ReleaseTempReg(pParse, r1);
107869
@@ -108969,28 +107878,28 @@
107878 }
107879
107880 /* Record the instruction used to terminate the loop. Disable
107881 ** WHERE clause terms made redundant by the index range scan.
107882 */
107883 if( pLoop->wsFlags & WHERE_ONEROW ){
107884 pLevel->op = OP_Noop;
107885 }else if( bRev ){
107886 pLevel->op = OP_Prev;
107887 }else{
107888 pLevel->op = OP_Next;
107889 }
107890 pLevel->p1 = iIdxCur;
107891 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
107892 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107893 }else{
107894 assert( pLevel->p5==0 );
107895 }
107896 }else
107897
107898 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
107899 if( pLoop->wsFlags & WHERE_MULTI_OR ){
107900 /* Case 5: Two or more separately indexed terms connected by OR
107901 **
107902 ** Example:
107903 **
107904 ** CREATE TABLE t1(a,b,c,d);
107905 ** CREATE INDEX i1 ON t1(a);
@@ -109039,11 +107948,11 @@
107948 int iRetInit; /* Address of regReturn init */
107949 int untestedTerms = 0; /* Some terms not completely tested */
107950 int ii; /* Loop counter */
107951 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
107952
107953 pTerm = pLoop->aLTerm[0];
107954 assert( pTerm!=0 );
107955 assert( pTerm->eOperator & WO_OR );
107956 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
107957 pOrWc = &pTerm->u.pOrInfo->wc;
107958 pLevel->op = OP_Return;
@@ -109058,11 +107967,11 @@
107967 struct SrcList_item *origSrc; /* Original list of tables */
107968 nNotReady = pWInfo->nLevel - iLevel - 1;
107969 pOrTab = sqlite3StackAllocRaw(pParse->db,
107970 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
107971 if( pOrTab==0 ) return notReady;
107972 pOrTab->nAlloc = (u8)(nNotReady + 1);
107973 pOrTab->nSrc = pOrTab->nAlloc;
107974 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
107975 origSrc = pWInfo->pTabList->a;
107976 for(k=1; k<=nNotReady; k++){
107977 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
@@ -109080,11 +107989,11 @@
107989 ** over the top of the loop into the body of it. In this case the
107990 ** correct response for the end-of-loop code (the OP_Return) is to
107991 ** fall through to the next instruction, just as an OP_Next does if
107992 ** called on an uninitialized cursor.
107993 */
107994 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107995 regRowset = ++pParse->nMem;
107996 regRowid = ++pParse->nMem;
107997 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
107998 }
107999 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
@@ -109131,15 +108040,15 @@
108040 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
108041 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
108042 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
108043 assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
108044 if( pSubWInfo ){
108045 WhereLoop *pSubLoop;
108046 explainOneScan(
108047 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
108048 );
108049 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108050 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
108051 int r;
108052 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
108053 regRowid, 0);
108054 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
@@ -109164,17 +108073,17 @@
108073 ** processed or the index is the same as that used by all previous
108074 ** terms, set pCov to the candidate covering index. Otherwise, set
108075 ** pCov to NULL to indicate that no candidate covering index will
108076 ** be available.
108077 */
108078 pSubLoop = pSubWInfo->a[0].pWLoop;
108079 assert( (pSubLoop->wsFlags & WHERE_TEMP_INDEX)==0 );
108080 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
108081 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
108082 ){
108083 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
108084 pCov = pSubLoop->u.btree.pIndex;
108085 }else{
108086 pCov = 0;
108087 }
108088
108089 /* Finish the loop through table entries that match term pOrTerm. */
@@ -109196,23 +108105,22 @@
108105 if( !untestedTerms ) disableTerm(pLevel, pTerm);
108106 }else
108107 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
108108
108109 {
108110 /* Case 6: There is no usable index. We must do a complete
108111 ** scan of the entire table.
108112 */
108113 static const u8 aStep[] = { OP_Next, OP_Prev };
108114 static const u8 aStart[] = { OP_Rewind, OP_Last };
108115 assert( bRev==0 || bRev==1 );
 
108116 pLevel->op = aStep[bRev];
108117 pLevel->p1 = iCur;
108118 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
108119 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108120 }
108121 newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
108122
108123 /* Insert code to test every subexpression that can be completely
108124 ** computed using the current set of tables.
108125 **
108126 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
@@ -109258,10 +108166,12 @@
108166 assert( !ExprHasProperty(pE, EP_FromJoin) );
108167 assert( (pTerm->prereqRight & newNotReady)!=0 );
108168 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
108169 if( pAlt==0 ) continue;
108170 if( pAlt->wtFlags & (TERM_CODED) ) continue;
108171 testcase( pAlt->eOperator & WO_EQ );
108172 testcase( pAlt->eOperator & WO_IN );
108173 VdbeNoopComment((v, "begin transitive constraint"));
108174 sEq = *pAlt->pExpr;
108175 sEq.pLeft = pE->pLeft;
108176 sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
108177 }
@@ -109290,51 +108200,1562 @@
108200 sqlite3ReleaseTempReg(pParse, iReleaseReg);
108201
108202 return newNotReady;
108203 }
108204
108205 #ifdef WHERETRACE_ENABLED
108206 /*
108207 ** Print a WhereLoop object for debugging purposes
 
 
 
108208 */
108209 static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
108210 int nb = 1+(pTabList->nSrc+7)/8;
108211 struct SrcList_item *pItem = pTabList->a + p->iTab;
108212 Table *pTab = pItem->pTab;
108213 sqlite3DebugPrintf("%c %2d.%0*llx.%0*llx", p->cId,
108214 p->iTab, nb, p->maskSelf, nb, p->prereq);
108215 sqlite3DebugPrintf(" %8s",
108216 pItem->zAlias ? pItem->zAlias : pTab->zName);
108217 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108218 if( p->u.btree.pIndex ){
108219 const char *zName = p->u.btree.pIndex->zName;
108220 if( zName==0 ) zName = "ipk";
108221 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
108222 int i = sqlite3Strlen30(zName) - 1;
108223 while( zName[i]!='_' ) i--;
108224 zName += i;
108225 }
108226 sqlite3DebugPrintf(".%-12s %2d", zName, p->u.btree.nEq);
108227 }else{
108228 sqlite3DebugPrintf("%16s","");
108229 }
108230 }else{
108231 char *z;
108232 if( p->u.vtab.idxStr ){
108233 z = sqlite3_mprintf("(%d,\"%s\",%x)",
108234 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
108235 }else{
108236 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
108237 }
108238 sqlite3DebugPrintf(" %-15s", z);
108239 sqlite3_free(z);
108240 }
108241 sqlite3DebugPrintf(" fg %05x N %d", p->wsFlags, p->nLTerm);
108242 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
108243 }
108244 #endif
108245
108246 /*
108247 ** Convert bulk memory into a valid WhereLoop that can be passed
108248 ** to whereLoopClear harmlessly.
108249 */
108250 static void whereLoopInit(WhereLoop *p){
108251 p->aLTerm = p->aLTermSpace;
108252 p->nLTerm = 0;
108253 p->nLSlot = ArraySize(p->aLTermSpace);
108254 p->wsFlags = 0;
108255 }
108256
108257 /*
108258 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
108259 */
108260 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
108261 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_TEMP_INDEX) ){
108262 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
108263 sqlite3_free(p->u.vtab.idxStr);
108264 p->u.vtab.needFree = 0;
108265 p->u.vtab.idxStr = 0;
108266 }else if( (p->wsFlags & WHERE_TEMP_INDEX)!=0 && p->u.btree.pIndex!=0 ){
108267 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
108268 sqlite3DbFree(db, p->u.btree.pIndex);
108269 p->u.btree.pIndex = 0;
108270 }
108271 }
108272 }
108273
108274 /*
108275 ** Deallocate internal memory used by a WhereLoop object
108276 */
108277 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
108278 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108279 whereLoopClearUnion(db, p);
108280 whereLoopInit(p);
108281 }
108282
108283 /*
108284 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
108285 */
108286 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
108287 WhereTerm **paNew;
108288 if( p->nLSlot>=n ) return SQLITE_OK;
108289 n = (n+7)&~7;
108290 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
108291 if( paNew==0 ) return SQLITE_NOMEM;
108292 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
108293 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108294 p->aLTerm = paNew;
108295 p->nLSlot = n;
108296 return SQLITE_OK;
108297 }
108298
108299 /*
108300 ** Transfer content from the second pLoop into the first.
108301 */
108302 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
108303 if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
108304 whereLoopClearUnion(db, pTo);
108305 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
108306 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
108307 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
108308 pFrom->u.vtab.needFree = 0;
108309 }else if( (pFrom->wsFlags & WHERE_TEMP_INDEX)!=0 ){
108310 pFrom->u.btree.pIndex = 0;
108311 }
108312 return SQLITE_OK;
108313 }
108314
108315 /*
108316 ** Delete a WhereLoop object
108317 */
108318 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
108319 whereLoopClear(db, p);
108320 sqlite3DbFree(db, p);
108321 }
108322
108323 /*
108324 ** Free a WhereInfo structure
108325 */
108326 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
108327 if( ALWAYS(pWInfo) ){
108328 whereClauseClear(&pWInfo->sWC);
108329 while( pWInfo->pLoops ){
108330 WhereLoop *p = pWInfo->pLoops;
108331 pWInfo->pLoops = p->pNextLoop;
108332 whereLoopDelete(db, p);
108333 }
 
 
 
 
 
 
 
 
 
 
 
 
 
108334 sqlite3DbFree(db, pWInfo);
108335 }
108336 }
108337
108338 /*
108339 ** Insert or replace a WhereLoop entry using the template supplied.
108340 **
108341 ** An existing WhereLoop entry might be overwritten if the new template
108342 ** is better and has fewer dependencies. Or the template will be ignored
108343 ** and no insert will occur if an existing WhereLoop is faster and has
108344 ** fewer dependencies than the template. Otherwise a new WhereLoop is
108345 ** added based on the template.
108346 **
108347 ** If pBuilder->pBest is not NULL then we only care about the very
108348 ** best template and that template should be stored in pBuilder->pBest.
108349 ** If pBuilder->pBest is NULL then a list of the best templates are stored
108350 ** in pBuilder->pWInfo->pLoops.
108351 **
108352 ** When accumulating multiple loops (when pBuilder->pBest is NULL) we
108353 ** still might overwrite similar loops with the new template if the
108354 ** template is better. Loops may be overwritten if the following
108355 ** conditions are met:
108356 **
108357 ** (1) They have the same iTab.
108358 ** (2) They have the same iSortIdx.
108359 ** (3) The template has same or fewer dependencies than the current loop
108360 ** (4) The template has the same or lower cost than the current loop
108361 ** (5) The template uses more terms of the same index but has no additional
108362 ** dependencies
108363 */
108364 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
108365 WhereLoop **ppPrev, *p, *pNext = 0;
108366 WhereInfo *pWInfo = pBuilder->pWInfo;
108367 sqlite3 *db = pWInfo->pParse->db;
108368
108369 /* If pBuilder->pBest is defined, then only keep track of the single
108370 ** best WhereLoop. pBuilder->pBest->maskSelf==0 indicates that no
108371 ** prior WhereLoops have been evaluated and that the current pTemplate
108372 ** is therefore the first and hence the best and should be retained.
108373 */
108374 if( (p = pBuilder->pBest)!=0 ){
108375 if( p->maskSelf!=0 ){
108376 WhereCost rCost = whereCostAdd(p->rRun,p->rSetup);
108377 WhereCost rTemplate = whereCostAdd(pTemplate->rRun,pTemplate->rSetup);
108378 if( rCost < rTemplate ){
108379 testcase( rCost==rTemplate-1 );
108380 goto whereLoopInsert_noop;
108381 }
108382 if( rCost==rTemplate && (p->prereq & pTemplate->prereq)==p->prereq ){
108383 goto whereLoopInsert_noop;
108384 }
108385 }
108386 #if WHERETRACE_ENABLED
108387 if( sqlite3WhereTrace & 0x8 ){
108388 sqlite3DebugPrintf(p->maskSelf==0 ? "ins-init: " : "ins-best: ");
108389 whereLoopPrint(pTemplate, pWInfo->pTabList);
108390 }
108391 #endif
108392 whereLoopXfer(db, p, pTemplate);
108393 return SQLITE_OK;
108394 }
108395
108396 /* Search for an existing WhereLoop to overwrite, or which takes
108397 ** priority over pTemplate.
108398 */
108399 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
108400 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
108401 /* If either the iTab or iSortIdx values for two WhereLoop are different
108402 ** then those WhereLoops need to be considered separately. Neither is
108403 ** a candidate to replace the other. */
108404 continue;
108405 }
108406 /* In the current implementation, the rSetup value is either zero
108407 ** or the cost of building an automatic index (NlogN) and the NlogN
108408 ** is the same for compatible WhereLoops. */
108409 assert( p->rSetup==0 || pTemplate->rSetup==0
108410 || p->rSetup==pTemplate->rSetup );
108411
108412 /* whereLoopAddBtree() always generates and inserts the automatic index
108413 ** case first. Hence compatible candidate WhereLoops never have a larger
108414 ** rSetup. Call this SETUP-INVARIANT */
108415 assert( p->rSetup>=pTemplate->rSetup );
108416
108417 if( (p->prereq & pTemplate->prereq)==p->prereq
108418 && p->rSetup<=pTemplate->rSetup
108419 && p->rRun<=pTemplate->rRun
108420 ){
108421 /* This branch taken when p is equal or better than pTemplate in
108422 ** all of (1) dependences (2) setup-cost, and (3) run-cost. */
108423 assert( p->rSetup==pTemplate->rSetup );
108424 if( p->nLTerm<pTemplate->nLTerm
108425 && (p->wsFlags & WHERE_INDEXED)!=0
108426 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
108427 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
108428 && p->prereq==pTemplate->prereq
108429 ){
108430 /* Overwrite an existing WhereLoop with an similar one that uses
108431 ** more terms of the index */
108432 pNext = p->pNextLoop;
108433 break;
108434 }else{
108435 /* pTemplate is not helpful.
108436 ** Return without changing or adding anything */
108437 goto whereLoopInsert_noop;
108438 }
108439 }
108440 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
108441 && p->rRun>=pTemplate->rRun
108442 && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
108443 ){
108444 /* Overwrite an existing WhereLoop with a better one: one that is
108445 ** better at one of (1) dependences, (2) setup-cost, or (3) run-cost
108446 ** and is no worse in any of those categories. */
108447 pNext = p->pNextLoop;
108448 break;
108449 }
108450 }
108451
108452 /* If we reach this point it means that either p[] should be overwritten
108453 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
108454 ** WhereLoop and insert it.
108455 */
108456 #if WHERETRACE_ENABLED
108457 if( sqlite3WhereTrace & 0x8 ){
108458 if( p!=0 ){
108459 sqlite3DebugPrintf("ins-del: ");
108460 whereLoopPrint(p, pWInfo->pTabList);
108461 }
108462 sqlite3DebugPrintf("ins-new: ");
108463 whereLoopPrint(pTemplate, pWInfo->pTabList);
108464 }
108465 #endif
108466 if( p==0 ){
108467 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
108468 if( p==0 ) return SQLITE_NOMEM;
108469 whereLoopInit(p);
108470 }
108471 whereLoopXfer(db, p, pTemplate);
108472 p->pNextLoop = pNext;
108473 *ppPrev = p;
108474 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108475 Index *pIndex = p->u.btree.pIndex;
108476 if( pIndex && pIndex->tnum==0 ){
108477 p->u.btree.pIndex = 0;
108478 }
108479 }
108480 return SQLITE_OK;
108481
108482 /* Jump here if the insert is a no-op */
108483 whereLoopInsert_noop:
108484 #if WHERETRACE_ENABLED
108485 if( sqlite3WhereTrace & 0x8 ){
108486 sqlite3DebugPrintf(pBuilder->pBest ? "ins-skip: " : "ins-noop: ");
108487 whereLoopPrint(pTemplate, pWInfo->pTabList);
108488 }
108489 #endif
108490 return SQLITE_OK;
108491 }
108492
108493 /*
108494 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
108495 ** Try to match one more.
108496 **
108497 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
108498 ** INTEGER PRIMARY KEY.
108499 */
108500 static int whereLoopAddBtreeIndex(
108501 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
108502 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
108503 Index *pProbe, /* An index on pSrc */
108504 WhereCost nInMul /* log(Number of iterations due to IN) */
108505 ){
108506 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
108507 Parse *pParse = pWInfo->pParse; /* Parsing context */
108508 sqlite3 *db = pParse->db; /* Database connection malloc context */
108509 WhereLoop *pNew; /* Template WhereLoop under construction */
108510 WhereTerm *pTerm; /* A WhereTerm under consideration */
108511 int opMask; /* Valid operators for constraints */
108512 WhereScan scan; /* Iterator for WHERE terms */
108513 Bitmask saved_prereq; /* Original value of pNew->prereq */
108514 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
108515 int saved_nEq; /* Original value of pNew->u.btree.nEq */
108516 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
108517 WhereCost saved_nOut; /* Original value of pNew->nOut */
108518 int iCol; /* Index of the column in the table */
108519 int rc = SQLITE_OK; /* Return code */
108520 WhereCost nRowEst; /* Estimated index selectivity */
108521 WhereCost rLogSize; /* Logarithm of table size */
108522 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
108523
108524 pNew = pBuilder->pNew;
108525 if( db->mallocFailed ) return SQLITE_NOMEM;
108526
108527 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
108528 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
108529 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
108530 opMask = WO_LT|WO_LE;
108531 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
108532 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
108533 }else{
108534 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
108535 }
108536 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
108537
108538 assert( pNew->u.btree.nEq<=pProbe->nColumn );
108539 if( pNew->u.btree.nEq < pProbe->nColumn ){
108540 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
108541 nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
108542 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
108543 }else{
108544 iCol = -1;
108545 nRowEst = 0;
108546 }
108547 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
108548 opMask, pProbe);
108549 saved_nEq = pNew->u.btree.nEq;
108550 saved_nLTerm = pNew->nLTerm;
108551 saved_wsFlags = pNew->wsFlags;
108552 saved_prereq = pNew->prereq;
108553 saved_nOut = pNew->nOut;
108554 pNew->rSetup = 0;
108555 rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
108556 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
108557 int nIn = 0;
108558 if( pTerm->prereqRight & pNew->maskSelf ) continue;
108559 pNew->wsFlags = saved_wsFlags;
108560 pNew->u.btree.nEq = saved_nEq;
108561 pNew->nLTerm = saved_nLTerm;
108562 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
108563 pNew->aLTerm[pNew->nLTerm++] = pTerm;
108564 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
108565 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
108566 if( pTerm->eOperator & WO_IN ){
108567 Expr *pExpr = pTerm->pExpr;
108568 pNew->wsFlags |= WHERE_COLUMN_IN;
108569 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
108570 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
108571 nIn = 46; assert( 46==whereCost(25) );
108572 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
108573 /* "x IN (value, value, ...)" */
108574 nIn = whereCost(pExpr->x.pList->nExpr);
108575 }
108576 pNew->rRun += nIn;
108577 pNew->u.btree.nEq++;
108578 pNew->nOut = nRowEst + nInMul + nIn;
108579 }else if( pTerm->eOperator & (WO_EQ) ){
108580 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
108581 || nInMul==0 );
108582 pNew->wsFlags |= WHERE_COLUMN_EQ;
108583 if( iCol<0
108584 || (pProbe->onError!=OE_None && nInMul==0
108585 && pNew->u.btree.nEq==pProbe->nColumn-1)
108586 ){
108587 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
108588 pNew->wsFlags |= WHERE_ONEROW;
108589 }
108590 pNew->u.btree.nEq++;
108591 pNew->nOut = nRowEst + nInMul;
108592 }else if( pTerm->eOperator & (WO_ISNULL) ){
108593 pNew->wsFlags |= WHERE_COLUMN_NULL;
108594 pNew->u.btree.nEq++;
108595 /* TUNING: IS NULL selects 2 rows */
108596 nIn = 10; assert( 10==whereCost(2) );
108597 pNew->nOut = nRowEst + nInMul + nIn;
108598 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
108599 testcase( pTerm->eOperator & WO_GT );
108600 testcase( pTerm->eOperator & WO_GE );
108601 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
108602 pBtm = pTerm;
108603 pTop = 0;
108604 }else{
108605 assert( pTerm->eOperator & (WO_LT|WO_LE) );
108606 testcase( pTerm->eOperator & WO_LT );
108607 testcase( pTerm->eOperator & WO_LE );
108608 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
108609 pTop = pTerm;
108610 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
108611 pNew->aLTerm[pNew->nLTerm-2] : 0;
108612 }
108613 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
108614 /* Adjust nOut and rRun for STAT3 range values */
108615 WhereCost rDiv;
108616 whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
108617 pBtm, pTop, &rDiv);
108618 pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
108619 }
108620 #ifdef SQLITE_ENABLE_STAT3
108621 if( pNew->u.btree.nEq==1 && pProbe->nSample ){
108622 tRowcnt nOut = 0;
108623 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
108624 testcase( pTerm->eOperator & WO_EQ );
108625 testcase( pTerm->eOperator & WO_ISNULL );
108626 rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
108627 }else if( (pTerm->eOperator & WO_IN)
108628 && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
108629 rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
108630 }
108631 if( rc==SQLITE_OK ) pNew->nOut = whereCost(nOut);
108632 }
108633 #endif
108634 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
108635 /* Each row involves a step of the index, then a binary search of
108636 ** the main table */
108637 pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
108638 }
108639 /* Step cost for each output row */
108640 pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
108641 /* TBD: Adjust nOut for additional constraints */
108642 rc = whereLoopInsert(pBuilder, pNew);
108643 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
108644 && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
108645 ){
108646 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
108647 }
108648 }
108649 pNew->prereq = saved_prereq;
108650 pNew->u.btree.nEq = saved_nEq;
108651 pNew->wsFlags = saved_wsFlags;
108652 pNew->nOut = saved_nOut;
108653 pNew->nLTerm = saved_nLTerm;
108654 return rc;
108655 }
108656
108657 /*
108658 ** Return True if it is possible that pIndex might be useful in
108659 ** implementing the ORDER BY clause in pBuilder.
108660 **
108661 ** Return False if pBuilder does not contain an ORDER BY clause or
108662 ** if there is no way for pIndex to be useful in implementing that
108663 ** ORDER BY clause.
108664 */
108665 static int indexMightHelpWithOrderBy(
108666 WhereLoopBuilder *pBuilder,
108667 Index *pIndex,
108668 int iCursor
108669 ){
108670 ExprList *pOB;
108671 int ii, jj;
108672
108673 if( pIndex->bUnordered ) return 0;
108674 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
108675 for(ii=0; ii<pOB->nExpr; ii++){
108676 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
108677 if( pExpr->op!=TK_COLUMN ) return 0;
108678 if( pExpr->iTable==iCursor ){
108679 for(jj=0; jj<pIndex->nColumn; jj++){
108680 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
108681 }
108682 }
108683 }
108684 return 0;
108685 }
108686
108687 /*
108688 ** Return a bitmask where 1s indicate that the corresponding column of
108689 ** the table is used by an index. Only the first 63 columns are considered.
108690 */
108691 static Bitmask columnsInIndex(Index *pIdx){
108692 Bitmask m = 0;
108693 int j;
108694 for(j=pIdx->nColumn-1; j>=0; j--){
108695 int x = pIdx->aiColumn[j];
108696 testcase( x==BMS-1 );
108697 testcase( x==BMS-2 );
108698 if( x<BMS-1 ) m |= MASKBIT(x);
108699 }
108700 return m;
108701 }
108702
108703
108704 /*
108705 ** Add all WhereLoop objects a single table of the join were the table
108706 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
108707 ** a b-tree table, not a virtual table.
108708 */
108709 static int whereLoopAddBtree(
108710 WhereLoopBuilder *pBuilder, /* WHERE clause information */
108711 Bitmask mExtra /* Extra prerequesites for using this table */
108712 ){
108713 WhereInfo *pWInfo; /* WHERE analysis context */
108714 Index *pProbe; /* An index we are evaluating */
108715 Index sPk; /* A fake index object for the primary key */
108716 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
108717 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
108718 SrcList *pTabList; /* The FROM clause */
108719 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
108720 WhereLoop *pNew; /* Template WhereLoop object */
108721 int rc = SQLITE_OK; /* Return code */
108722 int iSortIdx = 1; /* Index number */
108723 int b; /* A boolean value */
108724 WhereCost rSize; /* number of rows in the table */
108725 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
108726
108727 pNew = pBuilder->pNew;
108728 pWInfo = pBuilder->pWInfo;
108729 pTabList = pWInfo->pTabList;
108730 pSrc = pTabList->a + pNew->iTab;
108731 assert( !IsVirtual(pSrc->pTab) );
108732
108733 if( pSrc->pIndex ){
108734 /* An INDEXED BY clause specifies a particular index to use */
108735 pProbe = pSrc->pIndex;
108736 }else{
108737 /* There is no INDEXED BY clause. Create a fake Index object in local
108738 ** variable sPk to represent the rowid primary key index. Make this
108739 ** fake index the first in a chain of Index objects with all of the real
108740 ** indices to follow */
108741 Index *pFirst; /* First of real indices on the table */
108742 memset(&sPk, 0, sizeof(Index));
108743 sPk.nColumn = 1;
108744 sPk.aiColumn = &aiColumnPk;
108745 sPk.aiRowEst = aiRowEstPk;
108746 sPk.onError = OE_Replace;
108747 sPk.pTable = pSrc->pTab;
108748 aiRowEstPk[0] = pSrc->pTab->nRowEst;
108749 aiRowEstPk[1] = 1;
108750 pFirst = pSrc->pTab->pIndex;
108751 if( pSrc->notIndexed==0 ){
108752 /* The real indices of the table are only considered if the
108753 ** NOT INDEXED qualifier is omitted from the FROM clause */
108754 sPk.pNext = pFirst;
108755 }
108756 pProbe = &sPk;
108757 }
108758 rSize = whereCost(pSrc->pTab->nRowEst);
108759 rLogSize = estLog(rSize);
108760
108761 /* Automatic indexes */
108762 if( !pBuilder->pBest
108763 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
108764 && pSrc->pIndex==0
108765 && !pSrc->viaCoroutine
108766 && !pSrc->notIndexed
108767 && !pSrc->isCorrelated
108768 ){
108769 /* Generate auto-index WhereLoops */
108770 WhereClause *pWC = pBuilder->pWC;
108771 WhereTerm *pTerm;
108772 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
108773 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
108774 if( pTerm->prereqRight & pNew->maskSelf ) continue;
108775 if( termCanDriveIndex(pTerm, pSrc, 0) ){
108776 pNew->u.btree.nEq = 1;
108777 pNew->u.btree.pIndex = 0;
108778 pNew->nLTerm = 1;
108779 pNew->aLTerm[0] = pTerm;
108780 /* TUNING: One-time cost for computing the automatic index is
108781 ** approximately 6*N*log2(N) where N is the number of rows in
108782 ** the table being indexed. */
108783 pNew->rSetup = rLogSize + rSize + 26; assert( 26==whereCost(6) );
108784 /* TUNING: Each index lookup yields 10 rows in the table */
108785 pNew->nOut = 33; assert( 33==whereCost(10) );
108786 pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
108787 pNew->wsFlags = WHERE_TEMP_INDEX;
108788 pNew->prereq = mExtra | pTerm->prereqRight;
108789 rc = whereLoopInsert(pBuilder, pNew);
108790 }
108791 }
108792 }
108793
108794 /* Loop over all indices
108795 */
108796 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
108797 pNew->u.btree.nEq = 0;
108798 pNew->nLTerm = 0;
108799 pNew->iSortIdx = 0;
108800 pNew->rSetup = 0;
108801 pNew->prereq = mExtra;
108802 pNew->nOut = rSize;
108803 pNew->u.btree.pIndex = pProbe;
108804 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
108805 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
108806 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
108807 if( pProbe->tnum<=0 ){
108808 /* Integer primary key index */
108809 pNew->wsFlags = WHERE_IPK;
108810
108811 /* Full table scan */
108812 pNew->iSortIdx = b ? iSortIdx : 0;
108813 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
108814 ** + The extra 3 factor is to encourage the use of indexed lookups
108815 ** over full scans. A smaller constant 2 is used for covering
108816 ** index scans so that a covering index scan will be favored over
108817 ** a table scan. */
108818 pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
108819 rc = whereLoopInsert(pBuilder, pNew);
108820 if( rc ) break;
108821 }else{
108822 Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
108823 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
108824
108825 /* Full scan via index */
108826 if( b
108827 || ( m==0
108828 && pProbe->bUnordered==0
108829 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
108830 && sqlite3GlobalConfig.bUseCis
108831 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
108832 )
108833 ){
108834 pNew->iSortIdx = b ? iSortIdx : 0;
108835 if( m==0 ){
108836 /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
108837 ** + The extra 2 factor is to encourage the use of indexed lookups
108838 ** over index scans. A table scan uses a factor of 3 so that
108839 ** index scans are favored over table scans.
108840 ** + If this covering index might also help satisfy the ORDER BY
108841 ** clause, then the cost is fudged down slightly so that this
108842 ** index is favored above other indices that have no hope of
108843 ** helping with the ORDER BY. */
108844 pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
108845 }else{
108846 assert( b!=0 );
108847 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
108848 ** which we will simplify to just N*log2(N) */
108849 pNew->rRun = rSize + rLogSize;
108850 }
108851 rc = whereLoopInsert(pBuilder, pNew);
108852 if( rc ) break;
108853 }
108854 }
108855 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
108856
108857 /* If there was an INDEXED BY clause, then only that one index is
108858 ** considered. */
108859 if( pSrc->pIndex ) break;
108860 }
108861 return rc;
108862 }
108863
108864 #ifndef SQLITE_OMIT_VIRTUALTABLE
108865 /*
108866 ** Add all WhereLoop objects for a table of the join identified by
108867 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
108868 */
108869 static int whereLoopAddVirtual(
108870 WhereLoopBuilder *pBuilder /* WHERE clause information */
108871 ){
108872 WhereInfo *pWInfo; /* WHERE analysis context */
108873 Parse *pParse; /* The parsing context */
108874 WhereClause *pWC; /* The WHERE clause */
108875 struct SrcList_item *pSrc; /* The FROM clause term to search */
108876 Table *pTab;
108877 sqlite3 *db;
108878 sqlite3_index_info *pIdxInfo;
108879 struct sqlite3_index_constraint *pIdxCons;
108880 struct sqlite3_index_constraint_usage *pUsage;
108881 WhereTerm *pTerm;
108882 int i, j;
108883 int iTerm, mxTerm;
108884 int nConstraint;
108885 int seenIn = 0; /* True if an IN operator is seen */
108886 int seenVar = 0; /* True if a non-constant constraint is seen */
108887 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
108888 WhereLoop *pNew;
108889 int rc = SQLITE_OK;
108890
108891 pWInfo = pBuilder->pWInfo;
108892 pParse = pWInfo->pParse;
108893 db = pParse->db;
108894 pWC = pBuilder->pWC;
108895 pNew = pBuilder->pNew;
108896 pSrc = &pWInfo->pTabList->a[pNew->iTab];
108897 pTab = pSrc->pTab;
108898 assert( IsVirtual(pTab) );
108899 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
108900 if( pIdxInfo==0 ) return SQLITE_NOMEM;
108901 pNew->prereq = 0;
108902 pNew->rSetup = 0;
108903 pNew->wsFlags = WHERE_VIRTUALTABLE;
108904 pNew->nLTerm = 0;
108905 pNew->u.vtab.needFree = 0;
108906 pUsage = pIdxInfo->aConstraintUsage;
108907 nConstraint = pIdxInfo->nConstraint;
108908 if( whereLoopResize(db, pNew, nConstraint) ){
108909 sqlite3DbFree(db, pIdxInfo);
108910 return SQLITE_NOMEM;
108911 }
108912
108913 for(iPhase=0; iPhase<=3; iPhase++){
108914 if( !seenIn && (iPhase&1)!=0 ){
108915 iPhase++;
108916 if( iPhase>3 ) break;
108917 }
108918 if( !seenVar && iPhase>1 ) break;
108919 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108920 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
108921 j = pIdxCons->iTermOffset;
108922 pTerm = &pWC->a[j];
108923 switch( iPhase ){
108924 case 0: /* Constants without IN operator */
108925 pIdxCons->usable = 0;
108926 if( (pTerm->eOperator & WO_IN)!=0 ){
108927 seenIn = 1;
108928 }
108929 if( pTerm->prereqRight!=0 ){
108930 seenVar = 1;
108931 }else if( (pTerm->eOperator & WO_IN)==0 ){
108932 pIdxCons->usable = 1;
108933 }
108934 break;
108935 case 1: /* Constants with IN operators */
108936 assert( seenIn );
108937 pIdxCons->usable = (pTerm->prereqRight==0);
108938 break;
108939 case 2: /* Variables without IN */
108940 assert( seenVar );
108941 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
108942 break;
108943 default: /* Variables with IN */
108944 assert( seenVar && seenIn );
108945 pIdxCons->usable = 1;
108946 break;
108947 }
108948 }
108949 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
108950 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
108951 pIdxInfo->idxStr = 0;
108952 pIdxInfo->idxNum = 0;
108953 pIdxInfo->needToFreeIdxStr = 0;
108954 pIdxInfo->orderByConsumed = 0;
108955 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
108956 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
108957 if( rc ) goto whereLoopAddVtab_exit;
108958 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108959 pNew->prereq = 0;
108960 mxTerm = -1;
108961 assert( pNew->nLSlot>=nConstraint );
108962 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
108963 pNew->u.vtab.omitMask = 0;
108964 for(i=0; i<nConstraint; i++, pIdxCons++){
108965 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
108966 j = pIdxCons->iTermOffset;
108967 if( iTerm>=nConstraint
108968 || j<0
108969 || j>=pWC->nTerm
108970 || pNew->aLTerm[iTerm]!=0
108971 ){
108972 rc = SQLITE_ERROR;
108973 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
108974 goto whereLoopAddVtab_exit;
108975 }
108976 testcase( iTerm==nConstraint-1 );
108977 testcase( j==0 );
108978 testcase( j==pWC->nTerm-1 );
108979 pTerm = &pWC->a[j];
108980 pNew->prereq |= pTerm->prereqRight;
108981 assert( iTerm<pNew->nLSlot );
108982 pNew->aLTerm[iTerm] = pTerm;
108983 if( iTerm>mxTerm ) mxTerm = iTerm;
108984 testcase( iTerm==15 );
108985 testcase( iTerm==16 );
108986 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
108987 if( (pTerm->eOperator & WO_IN)!=0 ){
108988 if( pUsage[i].omit==0 ){
108989 /* Do not attempt to use an IN constraint if the virtual table
108990 ** says that the equivalent EQ constraint cannot be safely omitted.
108991 ** If we do attempt to use such a constraint, some rows might be
108992 ** repeated in the output. */
108993 break;
108994 }
108995 /* A virtual table that is constrained by an IN clause may not
108996 ** consume the ORDER BY clause because (1) the order of IN terms
108997 ** is not necessarily related to the order of output terms and
108998 ** (2) Multiple outputs from a single IN value will not merge
108999 ** together. */
109000 pIdxInfo->orderByConsumed = 0;
109001 }
109002 }
109003 }
109004 if( i>=nConstraint ){
109005 pNew->nLTerm = mxTerm+1;
109006 assert( pNew->nLTerm<=pNew->nLSlot );
109007 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
109008 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
109009 pIdxInfo->needToFreeIdxStr = 0;
109010 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
109011 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
109012 && pIdxInfo->orderByConsumed);
109013 pNew->rSetup = 0;
109014 pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
109015 /* TUNING: Every virtual table query returns 25 rows */
109016 pNew->nOut = 46; assert( 46==whereCost(25) );
109017 whereLoopInsert(pBuilder, pNew);
109018 if( pNew->u.vtab.needFree ){
109019 sqlite3_free(pNew->u.vtab.idxStr);
109020 pNew->u.vtab.needFree = 0;
109021 }
109022 }
109023 }
109024
109025 whereLoopAddVtab_exit:
109026 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
109027 sqlite3DbFree(db, pIdxInfo);
109028 return rc;
109029 }
109030 #endif /* SQLITE_OMIT_VIRTUALTABLE */
109031
109032 /*
109033 ** Add WhereLoop entries to handle OR terms. This works for either
109034 ** btrees or virtual tables.
109035 */
109036 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
109037 WhereInfo *pWInfo = pBuilder->pWInfo;
109038 WhereClause *pWC;
109039 WhereLoop *pNew;
109040 WhereTerm *pTerm, *pWCEnd;
109041 int rc = SQLITE_OK;
109042 int iCur;
109043 WhereClause tempWC;
109044 WhereLoopBuilder sSubBuild;
109045 WhereLoop sBest;
109046 struct SrcList_item *pItem;
109047
109048 pWC = pBuilder->pWC;
109049 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
109050 pWCEnd = pWC->a + pWC->nTerm;
109051 pNew = pBuilder->pNew;
109052
109053 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
109054 if( (pTerm->eOperator & WO_OR)!=0
109055 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
109056 ){
109057 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
109058 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
109059 WhereTerm *pOrTerm;
109060 WhereCost rTotal = 0;
109061 WhereCost nRow = 0;
109062 Bitmask prereq = mExtra;
109063
109064 whereLoopInit(&sBest);
109065 pItem = pWInfo->pTabList->a + pNew->iTab;
109066 iCur = pItem->iCursor;
109067 sSubBuild = *pBuilder;
109068 sSubBuild.pOrderBy = 0;
109069 sSubBuild.pBest = &sBest;
109070
109071 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
109072 if( (pOrTerm->eOperator & WO_AND)!=0 ){
109073 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
109074 }else if( pOrTerm->leftCursor==iCur ){
109075 tempWC.pWInfo = pWC->pWInfo;
109076 tempWC.pOuter = pWC;
109077 tempWC.op = TK_AND;
109078 tempWC.nTerm = 1;
109079 tempWC.a = pOrTerm;
109080 sSubBuild.pWC = &tempWC;
109081 }else{
109082 continue;
109083 }
109084 sBest.maskSelf = 0;
109085 sBest.rSetup = 0;
109086 sBest.rRun = 0;
109087 #ifndef SQLITE_OMIT_VIRTUALTABLE
109088 if( IsVirtual(pItem->pTab) ){
109089 rc = whereLoopAddVirtual(&sSubBuild);
109090 }else
109091 #endif
109092 {
109093 rc = whereLoopAddBtree(&sSubBuild, mExtra);
109094 }
109095 /* sBest.maskSelf is always zero if an error occurs */
109096 assert( rc==SQLITE_OK || sBest.maskSelf==0 );
109097 if( sBest.maskSelf==0 ) break;
109098 assert( sBest.rSetup==0 );
109099 rTotal = whereCostAdd(rTotal, sBest.rRun);
109100 nRow = whereCostAdd(nRow, sBest.nOut);
109101 prereq |= sBest.prereq;
109102 }
109103 assert( pNew->nLSlot>=1 );
109104 if( sBest.maskSelf ){
109105 pNew->nLTerm = 1;
109106 pNew->aLTerm[0] = pTerm;
109107 pNew->wsFlags = WHERE_MULTI_OR;
109108 pNew->rSetup = 0;
109109 /* TUNING: Multiple by 3.5 for the secondary table lookup */
109110 pNew->rRun = rTotal + 18; assert( 18==whereCost(7)-whereCost(2) );
109111 pNew->nOut = nRow;
109112 pNew->prereq = prereq;
109113 memset(&pNew->u, 0, sizeof(pNew->u));
109114 rc = whereLoopInsert(pBuilder, pNew);
109115 }
109116 whereLoopClear(pWInfo->pParse->db, &sBest);
109117 }
109118 }
109119 return rc;
109120 }
109121
109122 /*
109123 ** Add all WhereLoop objects for all tables
109124 */
109125 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
109126 WhereInfo *pWInfo = pBuilder->pWInfo;
109127 Bitmask mExtra = 0;
109128 Bitmask mPrior = 0;
109129 int iTab;
109130 SrcList *pTabList = pWInfo->pTabList;
109131 struct SrcList_item *pItem;
109132 sqlite3 *db = pWInfo->pParse->db;
109133 int nTabList = pWInfo->nLevel;
109134 int rc = SQLITE_OK;
109135 u8 priorJoinType = 0;
109136 WhereLoop *pNew;
109137
109138 /* Loop over the tables in the join, from left to right */
109139 pNew = pBuilder->pNew;
109140 whereLoopInit(pNew);
109141 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
109142 pNew->iTab = iTab;
109143 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
109144 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
109145 mExtra = mPrior;
109146 }
109147 priorJoinType = pItem->jointype;
109148 if( IsVirtual(pItem->pTab) ){
109149 rc = whereLoopAddVirtual(pBuilder);
109150 }else{
109151 rc = whereLoopAddBtree(pBuilder, mExtra);
109152 }
109153 if( rc==SQLITE_OK ){
109154 rc = whereLoopAddOr(pBuilder, mExtra);
109155 }
109156 mPrior |= pNew->maskSelf;
109157 if( rc || db->mallocFailed ) break;
109158 }
109159 whereLoopClear(db, pNew);
109160 return rc;
109161 }
109162
109163 /*
109164 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
109165 ** parameters) to see if it outputs rows in the requested ORDER BY
109166 ** (or GROUP BY) without requiring a separate source operation. Return:
109167 **
109168 ** 0: ORDER BY is not satisfied. Sorting required
109169 ** 1: ORDER BY is satisfied. Omit sorting
109170 ** -1: Unknown at this time
109171 **
109172 */
109173 static int wherePathSatisfiesOrderBy(
109174 WhereInfo *pWInfo, /* The WHERE clause */
109175 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
109176 WherePath *pPath, /* The WherePath to check */
109177 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
109178 u16 nLoop, /* Number of entries in pPath->aLoop[] */
109179 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
109180 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
109181 ){
109182 u8 revSet; /* True if rev is known */
109183 u8 rev; /* Composite sort order */
109184 u8 revIdx; /* Index sort order */
109185 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
109186 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
109187 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
109188 u16 nColumn; /* Number of columns in pIndex */
109189 u16 nOrderBy; /* Number terms in the ORDER BY clause */
109190 int iLoop; /* Index of WhereLoop in pPath being processed */
109191 int i, j; /* Loop counters */
109192 int iCur; /* Cursor number for current WhereLoop */
109193 int iColumn; /* A column number within table iCur */
109194 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
109195 WhereTerm *pTerm; /* A single term of the WHERE clause */
109196 Expr *pOBExpr; /* An expression from the ORDER BY clause */
109197 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
109198 Index *pIndex; /* The index associated with pLoop */
109199 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
109200 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
109201 Bitmask obDone; /* Mask of all ORDER BY terms */
109202 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
109203 Bitmask ready; /* Mask of inner loops */
109204
109205 /*
109206 ** We say the WhereLoop is "one-row" if it generates no more than one
109207 ** row of output. A WhereLoop is one-row if all of the following are true:
109208 ** (a) All index columns match with WHERE_COLUMN_EQ.
109209 ** (b) The index is unique
109210 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
109211 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
109212 **
109213 ** We say the WhereLoop is "order-distinct" if the set of columns from
109214 ** that WhereLoop that are in the ORDER BY clause are different for every
109215 ** row of the WhereLoop. Every one-row WhereLoop is automatically
109216 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
109217 ** is not order-distinct. To be order-distinct is not quite the same as being
109218 ** UNIQUE since a UNIQUE column or index can have multiple rows that
109219 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
109220 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
109221 **
109222 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
109223 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
109224 ** automatically order-distinct.
109225 */
109226
109227 assert( pOrderBy!=0 );
109228
109229 /* Sortability of virtual tables is determined by the xBestIndex method
109230 ** of the virtual table itself */
109231 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
109232 testcase( nLoop>0 ); /* True when outer loops are one-row and match
109233 ** no ORDER BY terms */
109234 return pLast->u.vtab.isOrdered;
109235 }
109236 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
109237
109238 nOrderBy = pOrderBy->nExpr;
109239 testcase( nOrderBy==BMS-1 );
109240 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
109241 isOrderDistinct = 1;
109242 obDone = MASKBIT(nOrderBy)-1;
109243 orderDistinctMask = 0;
109244 ready = 0;
109245 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
109246 if( iLoop>0 ) ready |= pLoop->maskSelf;
109247 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
109248 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
109249 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
109250
109251 /* Mark off any ORDER BY term X that is a column in the table of
109252 ** the current loop for which there is term in the WHERE
109253 ** clause of the form X IS NULL or X=? that reference only outer
109254 ** loops.
109255 */
109256 for(i=0; i<nOrderBy; i++){
109257 if( MASKBIT(i) & obSat ) continue;
109258 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109259 if( pOBExpr->op!=TK_COLUMN ) continue;
109260 if( pOBExpr->iTable!=iCur ) continue;
109261 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
109262 ~ready, WO_EQ|WO_ISNULL, 0);
109263 if( pTerm==0 ) continue;
109264 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
109265 const char *z1, *z2;
109266 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109267 if( !pColl ) pColl = db->pDfltColl;
109268 z1 = pColl->zName;
109269 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
109270 if( !pColl ) pColl = db->pDfltColl;
109271 z2 = pColl->zName;
109272 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
109273 }
109274 obSat |= MASKBIT(i);
109275 }
109276
109277 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
109278 if( pLoop->wsFlags & WHERE_IPK ){
109279 pIndex = 0;
109280 nColumn = 0;
109281 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
109282 return 0;
109283 }else{
109284 nColumn = pIndex->nColumn;
109285 isOrderDistinct = pIndex->onError!=OE_None;
109286 }
109287
109288 /* Loop through all columns of the index and deal with the ones
109289 ** that are not constrained by == or IN.
109290 */
109291 rev = revSet = 0;
109292 distinctColumns = 0;
109293 for(j=0; j<=nColumn; j++){
109294 u8 bOnce; /* True to run the ORDER BY search loop */
109295
109296 /* Skip over == and IS NULL terms */
109297 if( j<pLoop->u.btree.nEq
109298 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
109299 ){
109300 if( i & WO_ISNULL ){
109301 testcase( isOrderDistinct );
109302 isOrderDistinct = 0;
109303 }
109304 continue;
109305 }
109306
109307 /* Get the column number in the table (iColumn) and sort order
109308 ** (revIdx) for the j-th column of the index.
109309 */
109310 if( j<nColumn ){
109311 /* Normal index columns */
109312 iColumn = pIndex->aiColumn[j];
109313 revIdx = pIndex->aSortOrder[j];
109314 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
109315 }else{
109316 /* The ROWID column at the end */
109317 assert( j==nColumn );
109318 iColumn = -1;
109319 revIdx = 0;
109320 }
109321
109322 /* An unconstrained column that might be NULL means that this
109323 ** WhereLoop is not well-ordered
109324 */
109325 if( isOrderDistinct
109326 && iColumn>=0
109327 && j>=pLoop->u.btree.nEq
109328 && pIndex->pTable->aCol[iColumn].notNull==0
109329 ){
109330 isOrderDistinct = 0;
109331 }
109332
109333 /* Find the ORDER BY term that corresponds to the j-th column
109334 ** of the index and and mark that ORDER BY term off
109335 */
109336 bOnce = 1;
109337 isMatch = 0;
109338 for(i=0; bOnce && i<nOrderBy; i++){
109339 if( MASKBIT(i) & obSat ) continue;
109340 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109341 testcase( wctrlFlags & WHERE_GROUPBY );
109342 testcase( wctrlFlags & WHERE_DISTINCTBY );
109343 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
109344 if( pOBExpr->op!=TK_COLUMN ) continue;
109345 if( pOBExpr->iTable!=iCur ) continue;
109346 if( pOBExpr->iColumn!=iColumn ) continue;
109347 if( iColumn>=0 ){
109348 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109349 if( !pColl ) pColl = db->pDfltColl;
109350 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
109351 }
109352 isMatch = 1;
109353 break;
109354 }
109355 if( isMatch ){
109356 if( iColumn<0 ){
109357 testcase( distinctColumns==0 );
109358 distinctColumns = 1;
109359 }
109360 obSat |= MASKBIT(i);
109361 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
109362 /* Make sure the sort order is compatible in an ORDER BY clause.
109363 ** Sort order is irrelevant for a GROUP BY clause. */
109364 if( revSet ){
109365 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
109366 }else{
109367 rev = revIdx ^ pOrderBy->a[i].sortOrder;
109368 if( rev ) *pRevMask |= MASKBIT(iLoop);
109369 revSet = 1;
109370 }
109371 }
109372 }else{
109373 /* No match found */
109374 if( j==0 || j<nColumn ){
109375 testcase( isOrderDistinct!=0 );
109376 isOrderDistinct = 0;
109377 }
109378 break;
109379 }
109380 } /* end Loop over all index columns */
109381 if( distinctColumns ){
109382 testcase( isOrderDistinct==0 );
109383 isOrderDistinct = 1;
109384 }
109385 } /* end-if not one-row */
109386
109387 /* Mark off any other ORDER BY terms that reference pLoop */
109388 if( isOrderDistinct ){
109389 orderDistinctMask |= pLoop->maskSelf;
109390 for(i=0; i<nOrderBy; i++){
109391 Expr *p;
109392 if( MASKBIT(i) & obSat ) continue;
109393 p = pOrderBy->a[i].pExpr;
109394 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
109395 obSat |= MASKBIT(i);
109396 }
109397 }
109398 }
109399 } /* End the loop over all WhereLoops from outer-most down to inner-most */
109400 if( obSat==obDone ) return 1;
109401 if( !isOrderDistinct ) return 0;
109402 return -1;
109403 }
109404
109405 #ifdef WHERETRACE_ENABLED
109406 /* For debugging use only: */
109407 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
109408 static char zName[65];
109409 int i;
109410 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
109411 if( pLast ) zName[i++] = pLast->cId;
109412 zName[i] = 0;
109413 return zName;
109414 }
109415 #endif
109416
109417
109418 /*
109419 ** Given the list of WhereLoop objects on pWInfo->pLoops, this routine
109420 ** attempts to find the lowest cost path that visits each WhereLoop
109421 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
109422 **
109423 ** Assume that the total number of output rows that will need to be sorted
109424 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
109425 ** costs if nRowEst==0.
109426 **
109427 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
109428 ** error occurs.
109429 */
109430 static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
109431 int mxChoice; /* Maximum number of simultaneous paths tracked */
109432 int nLoop; /* Number of terms in the join */
109433 Parse *pParse; /* Parsing context */
109434 sqlite3 *db; /* The database connection */
109435 int iLoop; /* Loop counter over the terms of the join */
109436 int ii, jj; /* Loop counters */
109437 WhereCost rCost; /* Cost of a path */
109438 WhereCost mxCost = 0; /* Maximum cost of a set of paths */
109439 WhereCost rSortCost; /* Cost to do a sort */
109440 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
109441 WherePath *aFrom; /* All nFrom paths at the previous level */
109442 WherePath *aTo; /* The nTo best paths at the current level */
109443 WherePath *pFrom; /* An element of aFrom[] that we are working on */
109444 WherePath *pTo; /* An element of aTo[] that we are working on */
109445 WhereLoop *pWLoop; /* One of the WhereLoop objects */
109446 WhereLoop **pX; /* Used to divy up the pSpace memory */
109447 char *pSpace; /* Temporary memory used by this routine */
109448
109449 pParse = pWInfo->pParse;
109450 db = pParse->db;
109451 nLoop = pWInfo->nLevel;
109452 /* TUNING: For simple queries, only the best path is tracked.
109453 ** For 2-way joins, the 5 best paths are followed.
109454 ** For joins of 3 or more tables, track the 10 best paths */
109455 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
109456 assert( nLoop<=pWInfo->pTabList->nSrc );
109457 WHERETRACE(0x002, ("---- begin solver\n"));
109458
109459 /* Allocate and initialize space for aTo and aFrom */
109460 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
109461 pSpace = sqlite3DbMallocRaw(db, ii);
109462 if( pSpace==0 ) return SQLITE_NOMEM;
109463 aTo = (WherePath*)pSpace;
109464 aFrom = aTo+mxChoice;
109465 memset(aFrom, 0, sizeof(aFrom[0]));
109466 pX = (WhereLoop**)(aFrom+mxChoice);
109467 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
109468 pFrom->aLoop = pX;
109469 }
109470
109471 /* Seed the search with a single WherePath containing zero WhereLoops.
109472 **
109473 ** TUNING: Do not let the number of iterations go above 25. If the cost
109474 ** of computing an automatic index is not paid back within the first 25
109475 ** rows, then do not use the automatic index. */
109476 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
109477 nFrom = 1;
109478
109479 /* Precompute the cost of sorting the final result set, if the caller
109480 ** to sqlite3WhereBegin() was concerned about sorting */
109481 rSortCost = 0;
109482 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
109483 aFrom[0].isOrderedValid = 1;
109484 }else{
109485 /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
109486 ** number of output rows. */
109487 rSortCost = nRowEst + estLog(nRowEst);
109488 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
109489 }
109490
109491 /* Compute successively longer WherePaths using the previous generation
109492 ** of WherePaths as the basis for the next. Keep track of the mxChoice
109493 ** best paths at each generation */
109494 for(iLoop=0; iLoop<nLoop; iLoop++){
109495 nTo = 0;
109496 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
109497 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
109498 Bitmask maskNew;
109499 Bitmask revMask = 0;
109500 u8 isOrderedValid = pFrom->isOrderedValid;
109501 u8 isOrdered = pFrom->isOrdered;
109502 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
109503 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
109504 /* At this point, pWLoop is a candidate to be the next loop.
109505 ** Compute its cost */
109506 rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
109507 rCost = whereCostAdd(rCost, pFrom->rCost);
109508 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
109509 if( !isOrderedValid ){
109510 switch( wherePathSatisfiesOrderBy(pWInfo,
109511 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
109512 iLoop, pWLoop, &revMask) ){
109513 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
109514 isOrdered = 1;
109515 isOrderedValid = 1;
109516 break;
109517 case 0: /* No. pFrom+pWLoop will require a separate sort */
109518 isOrdered = 0;
109519 isOrderedValid = 1;
109520 rCost = whereCostAdd(rCost, rSortCost);
109521 break;
109522 default: /* Cannot tell yet. Try again on the next iteration */
109523 break;
109524 }
109525 }else{
109526 revMask = pFrom->revLoop;
109527 }
109528 /* Check to see if pWLoop should be added to the mxChoice best so far */
109529 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
109530 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
109531 testcase( jj==nTo-1 );
109532 break;
109533 }
109534 }
109535 if( jj>=nTo ){
109536 if( nTo>=mxChoice && rCost>=mxCost ){
109537 #ifdef WHERETRACE_ENABLED
109538 if( sqlite3WhereTrace&0x4 ){
109539 sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
109540 wherePathName(pFrom, iLoop, pWLoop), rCost,
109541 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109542 }
109543 #endif
109544 continue;
109545 }
109546 /* Add a new Path to the aTo[] set */
109547 if( nTo<mxChoice ){
109548 /* Increase the size of the aTo set by one */
109549 jj = nTo++;
109550 }else{
109551 /* New path replaces the prior worst to keep count below mxChoice */
109552 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
109553 }
109554 pTo = &aTo[jj];
109555 #ifdef WHERETRACE_ENABLED
109556 if( sqlite3WhereTrace&0x4 ){
109557 sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
109558 wherePathName(pFrom, iLoop, pWLoop), rCost,
109559 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109560 }
109561 #endif
109562 }else{
109563 if( pTo->rCost<=rCost ){
109564 #ifdef WHERETRACE_ENABLED
109565 if( sqlite3WhereTrace&0x4 ){
109566 sqlite3DebugPrintf(
109567 "Skip %s cost=%-3d order=%c",
109568 wherePathName(pFrom, iLoop, pWLoop), rCost,
109569 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109570 sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
109571 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109572 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109573 }
109574 #endif
109575 testcase( pTo->rCost==rCost );
109576 continue;
109577 }
109578 testcase( pTo->rCost==rCost+1 );
109579 /* A new and better score for a previously created equivalent path */
109580 #ifdef WHERETRACE_ENABLED
109581 if( sqlite3WhereTrace&0x4 ){
109582 sqlite3DebugPrintf(
109583 "Update %s cost=%-3d order=%c",
109584 wherePathName(pFrom, iLoop, pWLoop), rCost,
109585 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109586 sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
109587 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109588 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109589 }
109590 #endif
109591 }
109592 /* pWLoop is a winner. Add it to the set of best so far */
109593 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
109594 pTo->revLoop = revMask;
109595 pTo->nRow = pFrom->nRow + pWLoop->nOut;
109596 pTo->rCost = rCost;
109597 pTo->isOrderedValid = isOrderedValid;
109598 pTo->isOrdered = isOrdered;
109599 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
109600 pTo->aLoop[iLoop] = pWLoop;
109601 if( nTo>=mxChoice ){
109602 mxCost = aTo[0].rCost;
109603 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
109604 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
109605 }
109606 }
109607 }
109608 }
109609
109610 #ifdef WHERETRACE_ENABLED
109611 if( sqlite3WhereTrace>=2 ){
109612 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
109613 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
109614 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
109615 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
109616 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109617 if( pTo->isOrderedValid && pTo->isOrdered ){
109618 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
109619 }else{
109620 sqlite3DebugPrintf("\n");
109621 }
109622 }
109623 }
109624 #endif
109625
109626 /* Swap the roles of aFrom and aTo for the next generation */
109627 pFrom = aTo;
109628 aTo = aFrom;
109629 aFrom = pFrom;
109630 nFrom = nTo;
109631 }
109632
109633 if( nFrom==0 ){
109634 sqlite3ErrorMsg(pParse, "no query solution");
109635 sqlite3DbFree(db, pSpace);
109636 return SQLITE_ERROR;
109637 }
109638
109639 /* Find the lowest cost path. pFrom will be left pointing to that path */
109640 pFrom = aFrom;
109641 assert( nFrom==1 );
109642 #if 0 /* The following is needed if nFrom is ever more than 1 */
109643 for(ii=1; ii<nFrom; ii++){
109644 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
109645 }
109646 #endif
109647 assert( pWInfo->nLevel==nLoop );
109648 /* Load the lowest cost path into pWInfo */
109649 for(iLoop=0; iLoop<nLoop; iLoop++){
109650 WhereLevel *pLevel = pWInfo->a + iLoop;
109651 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
109652 pLevel->iFrom = pWLoop->iTab;
109653 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
109654 }
109655 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
109656 && pWInfo->pDistinct
109657 && nRowEst
109658 ){
109659 Bitmask notUsed;
109660 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinct, pFrom,
109661 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
109662 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109663 }
109664 if( pFrom->isOrdered ){
109665 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
109666 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109667 }else{
109668 pWInfo->bOBSat = 1;
109669 pWInfo->revMask = pFrom->revLoop;
109670 }
109671 }
109672 pWInfo->nRowOut = pFrom->nRow;
109673
109674 /* Free temporary memory and return success */
109675 sqlite3DbFree(db, pSpace);
109676 return SQLITE_OK;
109677 }
109678
109679 /*
109680 ** Most queries use only a single table (they are not joins) and have
109681 ** simple == constraints against indexed fields. This routine attempts
109682 ** to plan those simple cases using much less ceremony than the
109683 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
109684 ** times for the common case.
109685 **
109686 ** Return non-zero on success, if this query can be handled by this
109687 ** no-frills query planner. Return zero if this query needs the
109688 ** general-purpose query planner.
109689 */
109690 static int whereShortCut(WhereLoopBuilder *pBuilder){
109691 WhereInfo *pWInfo;
109692 struct SrcList_item *pItem;
109693 WhereClause *pWC;
109694 WhereTerm *pTerm;
109695 WhereLoop *pLoop;
109696 int iCur;
109697 int j;
109698 Table *pTab;
109699 Index *pIdx;
109700
109701 pWInfo = pBuilder->pWInfo;
109702 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
109703 assert( pWInfo->pTabList->nSrc>=1 );
109704 pItem = pWInfo->pTabList->a;
109705 pTab = pItem->pTab;
109706 if( IsVirtual(pTab) ) return 0;
109707 if( pItem->zIndex ) return 0;
109708 iCur = pItem->iCursor;
109709 pWC = &pWInfo->sWC;
109710 pLoop = pBuilder->pNew;
109711 pLoop->wsFlags = 0;
109712 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
109713 if( pTerm ){
109714 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
109715 pLoop->aLTerm[0] = pTerm;
109716 pLoop->nLTerm = 1;
109717 pLoop->u.btree.nEq = 1;
109718 /* TUNING: Cost of a rowid lookup is 10 */
109719 pLoop->rRun = 33; /* 33==whereCost(10) */
109720 }else{
109721 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109722 if( pIdx->onError==OE_None ) continue;
109723 for(j=0; j<pIdx->nColumn; j++){
109724 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
109725 if( pTerm==0 ) break;
109726 whereLoopResize(pWInfo->pParse->db, pLoop, j);
109727 pLoop->aLTerm[j] = pTerm;
109728 }
109729 if( j!=pIdx->nColumn ) continue;
109730 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
109731 if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
109732 pLoop->wsFlags |= WHERE_IDX_ONLY;
109733 }
109734 pLoop->nLTerm = j;
109735 pLoop->u.btree.nEq = j;
109736 pLoop->u.btree.pIndex = pIdx;
109737 /* TUNING: Cost of a unique index lookup is 15 */
109738 pLoop->rRun = 39; /* 39==whereCost(15) */
109739 break;
109740 }
109741 }
109742 if( pLoop->wsFlags ){
109743 pLoop->nOut = (WhereCost)1;
109744 pWInfo->a[0].pWLoop = pLoop;
109745 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
109746 pWInfo->a[0].iTabCur = iCur;
109747 pWInfo->nRowOut = 1;
109748 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
109749 if( pWInfo->pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109750 #ifdef SQLITE_DEBUG
109751 pLoop->cId = '0';
109752 #endif
109753 return 1;
109754 }
109755 return 0;
109756 }
109757
109758 /*
109759 ** Generate the beginning of the loop used for WHERE clause processing.
109760 ** The return value is a pointer to an opaque structure that contains
109761 ** information needed to terminate the loop. Later, the calling routine
@@ -109410,19 +109831,10 @@
109831 ** ORDER BY CLAUSE PROCESSING
109832 **
109833 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109834 ** if there is one. If there is no ORDER BY clause or if this routine
109835 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
 
 
 
 
 
 
 
 
 
109836 */
109837 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109838 Parse *pParse, /* The parser context */
109839 SrcList *pTabList, /* A list of all tables to be scanned */
109840 Expr *pWhere, /* The WHERE clause */
@@ -109434,22 +109846,21 @@
109846 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
109847 int nTabList; /* Number of elements in pTabList */
109848 WhereInfo *pWInfo; /* Will become the return value of this function */
109849 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
109850 Bitmask notReady; /* Cursors that are not yet positioned */
109851 WhereLoopBuilder sWLB; /* The WhereLoop builder */
109852 WhereMaskSet *pMaskSet; /* The expression mask set */
109853 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
 
 
109854 int ii; /* Loop counter */
109855 sqlite3 *db; /* Database connection */
109856 int rc; /* Return code */
109857
109858
109859 /* Variable initialization */
109860 memset(&sWLB, 0, sizeof(sWLB));
109861 sWLB.pOrderBy = pOrderBy;
109862
109863 /* The number of tables in the FROM clause is limited by the number of
109864 ** bits in a Bitmask
109865 */
109866 testcase( pTabList->nSrc==BMS );
@@ -109472,49 +109883,59 @@
109883 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
109884 ** some architectures. Hence the ROUND8() below.
109885 */
109886 db = pParse->db;
109887 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109888 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
 
 
 
 
109889 if( db->mallocFailed ){
109890 sqlite3DbFree(db, pWInfo);
109891 pWInfo = 0;
109892 goto whereBeginError;
109893 }
109894 pWInfo->nLevel = nTabList;
109895 pWInfo->pParse = pParse;
109896 pWInfo->pTabList = pTabList;
109897 pWInfo->pOrderBy = pOrderBy;
109898 pWInfo->pDistinct = pDistinct;
109899 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
 
109900 pWInfo->wctrlFlags = wctrlFlags;
109901 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109902 pMaskSet = &pWInfo->sMaskSet;
109903 sWLB.pWInfo = pWInfo;
109904 sWLB.pWC = &pWInfo->sWC;
109905 sWLB.pNew = (WhereLoop*)&pWInfo->a[nTabList];
109906 whereLoopInit(sWLB.pNew);
109907 #ifdef SQLITE_DEBUG
109908 sWLB.pNew->cId = '*';
109909 #endif
109910
109911 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109912 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109913 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109914
109915 /* Split the WHERE clause into separate subexpressions where each
109916 ** subexpression is separated by an AND operator.
109917 */
109918 initMaskSet(pMaskSet);
109919 whereClauseInit(&pWInfo->sWC, pWInfo);
109920 sqlite3ExprCodeConstants(pParse, pWhere);
109921 whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109922
109923 /* Special case: a WHERE clause that is constant. Evaluate the
109924 ** expression and either jump over all of the code or fall thru.
109925 */
109926 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109927 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109928 pWhere = 0;
109929 }
109930
109931 /* Special case: No FROM clause
109932 */
109933 if( nTabList==0 ){
109934 if( pOrderBy ) pWInfo->bOBSat = 1;
109935 if( pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109936 }
109937
109938 /* Assign a bit from the bitmask to every term in the FROM clause.
109939 **
109940 ** When assigning bitmask values to FROM clause cursors, it must be
109941 ** the case that if X is the bitmask for the N-th FROM clause term then
@@ -109547,337 +109968,153 @@
109968 /* Analyze all of the subexpressions. Note that exprAnalyze() might
109969 ** add new virtual terms onto the end of the WHERE clause. We do not
109970 ** want to analyze these virtual terms, so start analyzing at the end
109971 ** and work forward so that the added virtual terms are never processed.
109972 */
109973 exprAnalyzeAll(pTabList, &pWInfo->sWC);
109974 if( db->mallocFailed ){
109975 goto whereBeginError;
109976 }
109977
109978 /* If the ORDER BY (or GROUP BY) clause contains references to general
109979 ** expressions, then we won't be able to satisfy it using indices, so
109980 ** go ahead and disable it now.
109981 */
109982 if( pOrderBy && pDistinct ){
109983 for(ii=0; ii<pOrderBy->nExpr; ii++){
109984 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
109985 if( pExpr->op!=TK_COLUMN ){
109986 pWInfo->pOrderBy = pOrderBy = 0;
109987 break;
109988 }else if( pExpr->iColumn<0 ){
109989 break;
109990 }
109991 }
109992 }
109993
109994 /* Check if the DISTINCT qualifier, if there is one, is redundant.
109995 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109996 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109997 */
109998 if( pDistinct ){
109999 if( isDistinctRedundant(pParse,pTabList,&pWInfo->sWC,pDistinct) ){
110000 pDistinct = 0;
110001 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110002 }else if( pOrderBy==0 ){
110003 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
110004 pWInfo->pOrderBy = pDistinct;
110005 }
110006 }
110007
110008 /* Construct the WhereLoop objects */
110009 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
110010 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
110011 rc = whereLoopAddAll(&sWLB);
110012 if( rc ) goto whereBeginError;
110013
110014 /* Display all of the WhereLoop objects if wheretrace is enabled */
110015 #ifdef WHERETRACE_ENABLED
110016 if( sqlite3WhereTrace ){
110017 WhereLoop *p;
110018 int i = 0;
110019 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
110020 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
110021 for(p=pWInfo->pLoops; p; p=p->pNextLoop){
110022 p->cId = zLabel[(i++)%sizeof(zLabel)];
110023 whereLoopPrint(p, pTabList);
110024 }
110025 }
110026 #endif
110027
110028 wherePathSolver(pWInfo, 0);
110029 if( db->mallocFailed ) goto whereBeginError;
110030 if( pWInfo->pOrderBy ){
110031 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
110032 if( db->mallocFailed ) goto whereBeginError;
110033 }
110034 }
110035 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
110036 pWInfo->revMask = (Bitmask)(-1);
110037 }
110038 if( pParse->nErr || NEVER(db->mallocFailed) ){
110039 goto whereBeginError;
110040 }
110041 #ifdef WHERETRACE_ENABLED
110042 if( sqlite3WhereTrace ){
110043 int ii;
110044 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
110045 if( pWInfo->bOBSat ){
110046 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
110047 }
110048 switch( pWInfo->eDistinct ){
110049 case WHERE_DISTINCT_UNIQUE: {
110050 sqlite3DebugPrintf(" DISTINCT=unique");
110051 break;
110052 }
110053 case WHERE_DISTINCT_ORDERED: {
110054 sqlite3DebugPrintf(" DISTINCT=ordered");
110055 break;
110056 }
110057 case WHERE_DISTINCT_UNORDERED: {
110058 sqlite3DebugPrintf(" DISTINCT=unordered");
110059 break;
110060 }
110061 }
110062 sqlite3DebugPrintf("\n");
110063 for(ii=0; ii<nTabList; ii++){
110064 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
110065 }
110066 }
110067 #endif
110068 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
110069 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110070
110071 /* If the caller is an UPDATE or DELETE statement that is requesting
110072 ** to use a one-pass algorithm, determine if this is appropriate.
110073 ** The one-pass algorithm only works if the WHERE clause constraints
110074 ** the statement to update a single row.
110075 */
110076 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
110077 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
110078 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
110079 pWInfo->okOnePass = 1;
110080 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
110081 }
110082
110083 /* Open all tables in the pTabList and any indices selected for
110084 ** searching those tables.
110085 */
110086 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
110087 notReady = ~(Bitmask)0;
 
110088 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
110089 Table *pTab; /* Table to open */
110090 int iDb; /* Index of database containing table/index */
110091 struct SrcList_item *pTabItem;
110092 WhereLoop *pLoop;
110093
110094 pTabItem = &pTabList->a[pLevel->iFrom];
110095 pTab = pTabItem->pTab;
 
110096 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110097 pLoop = pLevel->pWLoop;
110098 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
110099 /* Do nothing */
110100 }else
110101 #ifndef SQLITE_OMIT_VIRTUALTABLE
110102 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
110103 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
110104 int iCur = pTabItem->iCursor;
110105 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
110106 }else if( IsVirtual(pTab) ){
110107 /* noop */
110108 }else
110109 #endif
110110 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110111 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
110112 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
110113 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
110114 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
110115 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
110116 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
110117 Bitmask b = pTabItem->colUsed;
110118 int n = 0;
110119 for(; b; b=b>>1, n++){}
110120 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
@@ -109886,26 +110123,27 @@
110123 }
110124 }else{
110125 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
110126 }
110127 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
110128 if( (pLoop->wsFlags & WHERE_TEMP_INDEX)!=0 ){
110129 constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
110130 }else
110131 #endif
110132 if( pLoop->wsFlags & WHERE_INDEXED ){
110133 Index *pIx = pLoop->u.btree.pIndex;
110134 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
110135 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
110136 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
110137 assert( pIx->pSchema==pTab->pSchema );
110138 assert( iIndexCur>=0 );
110139 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
110140 (char*)pKey, P4_KEYINFO_HANDOFF);
110141 VdbeComment((v, "%s", pIx->zName));
110142 }
110143 sqlite3CodeVerifySchema(pParse, iDb);
110144 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
110145 }
110146 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
110147 if( db->mallocFailed ) goto whereBeginError;
110148
110149 /* Generate the code to do the search. Each iteration of the for
@@ -109914,70 +110152,15 @@
110152 */
110153 notReady = ~(Bitmask)0;
110154 for(ii=0; ii<nTabList; ii++){
110155 pLevel = &pWInfo->a[ii];
110156 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
110157 notReady = codeOneLoopStart(pWInfo, ii, notReady);
110158 pWInfo->iContinue = pLevel->addrCont;
110159 }
110160
110161 /* Done. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110162 return pWInfo;
110163
110164 /* Jump here if malloc fails */
110165 whereBeginError:
110166 if( pWInfo ){
@@ -109994,24 +110177,26 @@
110177 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
110178 Parse *pParse = pWInfo->pParse;
110179 Vdbe *v = pParse->pVdbe;
110180 int i;
110181 WhereLevel *pLevel;
110182 WhereLoop *pLoop;
110183 SrcList *pTabList = pWInfo->pTabList;
110184 sqlite3 *db = pParse->db;
110185
110186 /* Generate loop termination code.
110187 */
110188 sqlite3ExprCacheClear(pParse);
110189 for(i=pWInfo->nLevel-1; i>=0; i--){
110190 pLevel = &pWInfo->a[i];
110191 pLoop = pLevel->pWLoop;
110192 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110193 if( pLevel->op!=OP_Noop ){
110194 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110195 sqlite3VdbeChangeP5(v, pLevel->p5);
110196 }
110197 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110198 struct InLoop *pIn;
110199 int j;
110200 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110201 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110202 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
@@ -110022,16 +110207,16 @@
110207 }
110208 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110209 if( pLevel->iLeftJoin ){
110210 int addr;
110211 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110212 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110213 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
110214 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
110215 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110216 }
110217 if( pLoop->wsFlags & WHERE_INDEXED ){
110218 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110219 }
110220 if( pLevel->op==OP_Return ){
110221 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110222 }else{
@@ -110052,42 +110237,41 @@
110237 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110238 Index *pIdx = 0;
110239 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110240 Table *pTab = pTabItem->pTab;
110241 assert( pTab!=0 );
110242 pLoop = pLevel->pWLoop;
110243 if( (pTab->tabFlags & TF_Ephemeral)==0
110244 && pTab->pSelect==0
110245 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110246 ){
110247 int ws = pLoop->wsFlags;
110248 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110249 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110250 }
110251 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_TEMP_INDEX))==0 ){
110252 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110253 }
110254 }
110255
110256 /* If this scan uses an index, make VDBE code substitutions to read data
110257 ** from the index instead of from the table where possible. In some cases
110258 ** this optimization prevents the table from ever being read, which can
110259 ** yield a significant performance boost.
 
 
110260 **
110261 ** Calls to the code generator in between sqlite3WhereBegin and
110262 ** sqlite3WhereEnd will have created code that references the table
110263 ** directly. This loop scans all that code looking for opcodes
110264 ** that reference the table and converts them into opcodes that
110265 ** reference the index.
110266 */
110267 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
110268 pIdx = pLoop->u.btree.pIndex;
110269 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
110270 pIdx = pLevel->u.pCovidx;
110271 }
110272 if( pIdx && !db->mallocFailed ){
110273 int k, j, last;
110274 VdbeOp *pOp;
110275
110276 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110277 last = sqlite3VdbeCurrentAddr(v);
@@ -110099,12 +110283,11 @@
110283 pOp->p2 = j;
110284 pOp->p1 = pLevel->iIdxCur;
110285 break;
110286 }
110287 }
110288 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
 
110289 }else if( pOp->opcode==OP_Rowid ){
110290 pOp->p1 = pLevel->iIdxCur;
110291 pOp->opcode = OP_IdxRowid;
110292 }
110293 }
@@ -115480,11 +115663,11 @@
115663 }
115664
115665 /*
115666 ** Another built-in collating sequence: NOCASE.
115667 **
115668 ** This collating sequence is intended to be used for "case independent
115669 ** comparison". SQLite's knowledge of upper and lower case equivalents
115670 ** extends only to the 26 characters used in the English language.
115671 **
115672 ** At the moment there is only a UTF-8 implementation.
115673 */
@@ -115627,16 +115810,10 @@
115810 "statements or unfinished backups");
115811 sqlite3_mutex_leave(db->mutex);
115812 return SQLITE_BUSY;
115813 }
115814
 
 
 
 
 
 
115815 #ifdef SQLITE_ENABLE_SQLLOG
115816 if( sqlite3GlobalConfig.xSqllog ){
115817 /* Closing the handle. Fourth parameter is passed the value 2. */
115818 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115819 }
@@ -115686,10 +115863,16 @@
115863 /* If we reach this point, it means that the database connection has
115864 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
115865 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
115866 ** go ahead and free all resources.
115867 */
115868
115869 /* If a transaction is open, roll it back. This also ensures that if
115870 ** any database schemas have been modified by an uncommitted transaction
115871 ** they are reset. And that the required b-tree mutex is held to make
115872 ** the pager rollback and schema reset an atomic operation. */
115873 sqlite3RollbackAll(db, SQLITE_OK);
115874
115875 /* Free any outstanding Savepoint structures. */
115876 sqlite3CloseSavepoints(db);
115877
115878 /* Close all database connections */
@@ -115787,19 +115970,26 @@
115970 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115971 int i;
115972 int inTrans = 0;
115973 assert( sqlite3_mutex_held(db->mutex) );
115974 sqlite3BeginBenignMalloc();
115975
115976 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
115977 ** This is important in case the transaction being rolled back has
115978 ** modified the database schema. If the b-tree mutexes are not taken
115979 ** here, then another shared-cache connection might sneak in between
115980 ** the database rollback and schema reset, which can cause false
115981 ** corruption reports in some cases. */
115982 sqlite3BtreeEnterAll(db);
115983
115984 for(i=0; i<db->nDb; i++){
115985 Btree *p = db->aDb[i].pBt;
115986 if( p ){
115987 if( sqlite3BtreeIsInTrans(p) ){
115988 inTrans = 1;
115989 }
115990 sqlite3BtreeRollback(p, tripCode);
 
115991 }
115992 }
115993 sqlite3VtabRollback(db);
115994 sqlite3EndBenignMalloc();
115995
@@ -117562,12 +117752,10 @@
117752 /*
117753 ** Test to see whether or not the database connection is in autocommit
117754 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
117755 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
117756 ** by the next COMMIT or ROLLBACK.
 
 
117757 */
117758 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117759 return db->autoCommit;
117760 }
117761
@@ -119051,10 +119239,22 @@
119239
119240 #endif /* _FTS3_HASH_H_ */
119241
119242 /************** End of fts3_hash.h *******************************************/
119243 /************** Continuing where we left off in fts3Int.h ********************/
119244
119245 /*
119246 ** This constant determines the maximum depth of an FTS expression tree
119247 ** that the library will create and use. FTS uses recursion to perform
119248 ** various operations on the query tree, so the disadvantage of a large
119249 ** limit is that it may allow very large queries to use large amounts
119250 ** of stack space (perhaps causing a stack overflow).
119251 */
119252 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
119253 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
119254 #endif
119255
119256
119257 /*
119258 ** This constant controls how often segments are merged. Once there are
119259 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119260 ** segment of level N+1.
@@ -120709,11 +120909,11 @@
120909 /* By default use a full table scan. This is an expensive option,
120910 ** so search through the constraints to see if a more efficient
120911 ** strategy is possible.
120912 */
120913 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120914 pInfo->estimatedCost = 5000000;
120915 for(i=0; i<pInfo->nConstraint; i++){
120916 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120917 if( pCons->usable==0 ) continue;
120918
120919 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
@@ -122270,15 +122470,11 @@
122470 );
122471 if( rc!=SQLITE_OK ){
122472 return rc;
122473 }
122474
 
 
 
122475 rc = fts3EvalStart(pCsr);
 
122476 sqlite3Fts3SegmentsClose(p);
122477 if( rc!=SQLITE_OK ) return rc;
122478 pCsr->pNextId = pCsr->aDoclist;
122479 pCsr->iPrevId = 0;
122480 }
@@ -126129,30 +126325,30 @@
126325 int iDefaultCol, /* Default column to query */
126326 const char *z, int n, /* Text of MATCH query */
126327 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
126328 char **pzErr /* OUT: Error message (sqlite3_malloc) */
126329 ){
 
126330 int rc = fts3ExprParseUnbalanced(
126331 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126332 );
126333
126334 /* Rebalance the expression. And check that its depth does not exceed
126335 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
126336 if( rc==SQLITE_OK && *ppExpr ){
126337 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126338 if( rc==SQLITE_OK ){
126339 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126340 }
126341 }
126342
126343 if( rc!=SQLITE_OK ){
126344 sqlite3Fts3ExprFree(*ppExpr);
126345 *ppExpr = 0;
126346 if( rc==SQLITE_TOOBIG ){
126347 *pzErr = sqlite3_mprintf(
126348 "FTS expression tree is too large (maximum depth %d)",
126349 SQLITE_FTS3_MAX_EXPR_DEPTH
126350 );
126351 rc = SQLITE_ERROR;
126352 }else if( rc==SQLITE_ERROR ){
126353 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126354 }
@@ -129110,41 +129306,34 @@
129306 *pRC = rc;
129307 }
129308
129309
129310 /*
129311 ** This function ensures that the caller has obtained an exclusive
129312 ** shared-cache table-lock on the %_segdir table. This is required before
129313 ** writing data to the fts3 table. If this lock is not acquired first, then
129314 ** the caller may end up attempting to take this lock as part of committing
129315 ** a transaction, causing SQLite to return SQLITE_LOCKED or
129316 ** LOCKED_SHAREDCACHEto a COMMIT command.
129317 **
129318 ** It is best to avoid this because if FTS3 returns any error when
129319 ** committing a transaction, the whole transaction will be rolled back.
129320 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
129321 ** It can still happen if the user locks the underlying tables directly
129322 ** instead of accessing them via FTS.
129323 */
129324 static int fts3Writelock(Fts3Table *p){
129325 int rc = SQLITE_OK;
129326
129327 if( p->nPendingData==0 ){
129328 sqlite3_stmt *pStmt;
129329 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
 
 
 
 
 
129330 if( rc==SQLITE_OK ){
129331 sqlite3_bind_null(pStmt, 1);
129332 sqlite3_step(pStmt);
129333 rc = sqlite3_reset(pStmt);
129334 }
 
 
129335 }
129336
129337 return rc;
129338 }
129339
@@ -133918,10 +134107,13 @@
134107 goto update_out;
134108 }
134109 aSzIns = &aSzDel[p->nColumn+1];
134110 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
134111
134112 rc = fts3Writelock(p);
134113 if( rc!=SQLITE_OK ) goto update_out;
134114
134115 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
134116 ** value, then this operation requires constraint handling.
134117 **
134118 ** If the on-conflict mode is REPLACE, this means that the existing row
134119 ** should be deleted from the database before inserting the new row. Or,
@@ -136051,32 +136243,31 @@
136243 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136244 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136245 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136246 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136247 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136248 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
136249 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
136250 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
136251 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
136252 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
136253 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
136254 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
136255 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
136256 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
136257 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
136258 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
136259 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
136260 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
136261 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
136262 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
136263 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
136264 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
136265 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
136266 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
136267 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
136268 0x380400F0,
 
136269 };
136270 static const unsigned int aAscii[4] = {
136271 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136272 };
136273
@@ -139705,11 +139896,11 @@
139896 ** operator) using the ICU uregex_XX() APIs.
139897 **
139898 ** * Implementations of the SQL scalar upper() and lower() functions
139899 ** for case mapping.
139900 **
139901 ** * Integration of ICU and SQLite collation sequences.
139902 **
139903 ** * An implementation of the LIKE operator that uses ICU to
139904 ** provide case-independent matching.
139905 */
139906
139907
+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-20 14:17:39 d94db3fd921890ab1d6414ab629410ae50779686"
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-20 14:17:39 d94db3fd921890ab1d6414ab629410ae50779686"
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/stat.c
+++ src/stat.c
@@ -252,11 +252,11 @@
252252
style_header("URLs and Checkouts");
253253
style_submenu_element("Stat", "Repository Stats", "stat");
254254
@ <div class="section">URLs</div>
255255
@ <table border="0" width='100%%'>
256256
db_prepare(&q, "SELECT substr(name,9), datetime(mtime,'unixepoch')"
257
- " FROM config WHERE name GLOB 'baseurl:*' ORDER BY 2");
257
+ " FROM config WHERE name GLOB 'baseurl:*' ORDER BY 2 DESC");
258258
cnt = 0;
259259
while( db_step(&q)==SQLITE_ROW ){
260260
@ <tr><td width='100%%'>%h(db_column_text(&q,0))</td>
261261
@ <td><nobr>%h(db_column_text(&q,1))</nobr></td></tr>
262262
cnt++;
@@ -267,11 +267,11 @@
267267
}
268268
@ </table>
269269
@ <div class="section">Checkouts</div>
270270
@ <table border="0" width='100%%'>
271271
db_prepare(&q, "SELECT substr(name,7), datetime(mtime,'unixepoch')"
272
- " FROM config WHERE name GLOB 'ckout:*' ORDER BY 2");
272
+ " FROM config WHERE name GLOB 'ckout:*' ORDER BY 2 DESC");
273273
cnt = 0;
274274
while( db_step(&q)==SQLITE_ROW ){
275275
@ <tr><td width='100%%'>%h(db_column_text(&q,0))</td>
276276
@ <td><nobr>%h(db_column_text(&q,1))</nobr></td></tr>
277277
cnt++;
278278
--- src/stat.c
+++ src/stat.c
@@ -252,11 +252,11 @@
252 style_header("URLs and Checkouts");
253 style_submenu_element("Stat", "Repository Stats", "stat");
254 @ <div class="section">URLs</div>
255 @ <table border="0" width='100%%'>
256 db_prepare(&q, "SELECT substr(name,9), datetime(mtime,'unixepoch')"
257 " FROM config WHERE name GLOB 'baseurl:*' ORDER BY 2");
258 cnt = 0;
259 while( db_step(&q)==SQLITE_ROW ){
260 @ <tr><td width='100%%'>%h(db_column_text(&q,0))</td>
261 @ <td><nobr>%h(db_column_text(&q,1))</nobr></td></tr>
262 cnt++;
@@ -267,11 +267,11 @@
267 }
268 @ </table>
269 @ <div class="section">Checkouts</div>
270 @ <table border="0" width='100%%'>
271 db_prepare(&q, "SELECT substr(name,7), datetime(mtime,'unixepoch')"
272 " FROM config WHERE name GLOB 'ckout:*' ORDER BY 2");
273 cnt = 0;
274 while( db_step(&q)==SQLITE_ROW ){
275 @ <tr><td width='100%%'>%h(db_column_text(&q,0))</td>
276 @ <td><nobr>%h(db_column_text(&q,1))</nobr></td></tr>
277 cnt++;
278
--- src/stat.c
+++ src/stat.c
@@ -252,11 +252,11 @@
252 style_header("URLs and Checkouts");
253 style_submenu_element("Stat", "Repository Stats", "stat");
254 @ <div class="section">URLs</div>
255 @ <table border="0" width='100%%'>
256 db_prepare(&q, "SELECT substr(name,9), datetime(mtime,'unixepoch')"
257 " FROM config WHERE name GLOB 'baseurl:*' ORDER BY 2 DESC");
258 cnt = 0;
259 while( db_step(&q)==SQLITE_ROW ){
260 @ <tr><td width='100%%'>%h(db_column_text(&q,0))</td>
261 @ <td><nobr>%h(db_column_text(&q,1))</nobr></td></tr>
262 cnt++;
@@ -267,11 +267,11 @@
267 }
268 @ </table>
269 @ <div class="section">Checkouts</div>
270 @ <table border="0" width='100%%'>
271 db_prepare(&q, "SELECT substr(name,7), datetime(mtime,'unixepoch')"
272 " FROM config WHERE name GLOB 'ckout:*' ORDER BY 2 DESC");
273 cnt = 0;
274 while( db_step(&q)==SQLITE_ROW ){
275 @ <tr><td width='100%%'>%h(db_column_text(&q,0))</td>
276 @ <td><nobr>%h(db_column_text(&q,1))</nobr></td></tr>
277 cnt++;
278
+14 -2
--- src/th.c
+++ src/th.c
@@ -1874,12 +1874,24 @@
18741874
18751875
if( rc==TH_OK && eArgType==ARG_INTEGER ){
18761876
int iRes = 0;
18771877
switch( pExpr->pOp->eOp ) {
18781878
case OP_MULTIPLY: iRes = iLeft*iRight; break;
1879
- case OP_DIVIDE: iRes = iLeft/iRight; break;
1880
- case OP_MODULUS: iRes = iLeft%iRight; break;
1879
+ case OP_DIVIDE:
1880
+ if(!iRight){
1881
+ Th_ErrorMessage(interp, "Divide by 0:", zLeft, nLeft);
1882
+ return TH_ERROR;
1883
+ }
1884
+ iRes = iLeft/iRight;
1885
+ break;
1886
+ case OP_MODULUS:
1887
+ if(!iRight){
1888
+ Th_ErrorMessage(interp, "Modulo by 0:", zLeft, nLeft);
1889
+ return TH_ERROR;
1890
+ }
1891
+ iRes = iLeft%iRight;
1892
+ break;
18811893
case OP_ADD: iRes = iLeft+iRight; break;
18821894
case OP_SUBTRACT: iRes = iLeft-iRight; break;
18831895
case OP_LEFTSHIFT: iRes = iLeft<<iRight; break;
18841896
case OP_RIGHTSHIFT: iRes = iLeft>>iRight; break;
18851897
case OP_LT: iRes = iLeft<iRight; break;
18861898
--- src/th.c
+++ src/th.c
@@ -1874,12 +1874,24 @@
1874
1875 if( rc==TH_OK && eArgType==ARG_INTEGER ){
1876 int iRes = 0;
1877 switch( pExpr->pOp->eOp ) {
1878 case OP_MULTIPLY: iRes = iLeft*iRight; break;
1879 case OP_DIVIDE: iRes = iLeft/iRight; break;
1880 case OP_MODULUS: iRes = iLeft%iRight; break;
 
 
 
 
 
 
 
 
 
 
 
 
1881 case OP_ADD: iRes = iLeft+iRight; break;
1882 case OP_SUBTRACT: iRes = iLeft-iRight; break;
1883 case OP_LEFTSHIFT: iRes = iLeft<<iRight; break;
1884 case OP_RIGHTSHIFT: iRes = iLeft>>iRight; break;
1885 case OP_LT: iRes = iLeft<iRight; break;
1886
--- src/th.c
+++ src/th.c
@@ -1874,12 +1874,24 @@
1874
1875 if( rc==TH_OK && eArgType==ARG_INTEGER ){
1876 int iRes = 0;
1877 switch( pExpr->pOp->eOp ) {
1878 case OP_MULTIPLY: iRes = iLeft*iRight; break;
1879 case OP_DIVIDE:
1880 if(!iRight){
1881 Th_ErrorMessage(interp, "Divide by 0:", zLeft, nLeft);
1882 return TH_ERROR;
1883 }
1884 iRes = iLeft/iRight;
1885 break;
1886 case OP_MODULUS:
1887 if(!iRight){
1888 Th_ErrorMessage(interp, "Modulo by 0:", zLeft, nLeft);
1889 return TH_ERROR;
1890 }
1891 iRes = iLeft%iRight;
1892 break;
1893 case OP_ADD: iRes = iLeft+iRight; break;
1894 case OP_SUBTRACT: iRes = iLeft-iRight; break;
1895 case OP_LEFTSHIFT: iRes = iLeft<<iRight; break;
1896 case OP_RIGHTSHIFT: iRes = iLeft>>iRight; break;
1897 case OP_LT: iRes = iLeft<iRight; break;
1898
+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
+7 -11
--- src/vfile.c
+++ src/vfile.c
@@ -432,20 +432,16 @@
432432
**
433433
** Any files or directories that match the glob pattern pIgnore are
434434
** excluded from the scan. Name matching occurs after the first
435435
** nPrefix characters are elided from the filename.
436436
*/
437
-void vfile_scan(Blob *pPath, int nPrefix, unsigned scanFlags, Glob *pIgnore){
438
- vfile_scan2(pPath, nPrefix, scanFlags, pIgnore, 0);
439
-}
440
-
441
-void vfile_scan2(
442
- Blob *pPath,
443
- int nPrefix,
444
- unsigned scanFlags,
445
- Glob *pIgnore1,
446
- Glob *pIgnore2
437
+void vfile_scan(
438
+ Blob *pPath, /* Directory to be scanned */
439
+ int nPrefix, /* Number of bytes in directory name */
440
+ unsigned scanFlags, /* Zero or more SCAN_xxx flags */
441
+ Glob *pIgnore1, /* Do not add files that match this GLOB */
442
+ Glob *pIgnore2 /* Omit files matching this GLOB too */
447443
){
448444
DIR *d;
449445
int origSize;
450446
const char *zDir;
451447
struct dirent *pEntry;
@@ -490,11 +486,11 @@
490486
if( glob_match(pIgnore1, &zPath[nPrefix+1]) ||
491487
glob_match(pIgnore2, &zPath[nPrefix+1]) ){
492488
/* do nothing */
493489
}else if( file_wd_isdir(zPath)==1 ){
494490
if( !vfile_top_of_checkout(zPath) ){
495
- vfile_scan2(pPath, nPrefix, scanFlags, pIgnore1, pIgnore2);
491
+ vfile_scan(pPath, nPrefix, scanFlags, pIgnore1, pIgnore2);
496492
}
497493
}else if( file_wd_isfile_or_link(zPath) ){
498494
if( (scanFlags & SCAN_TEMP)==0 || is_temporary_file(zUtf8) ){
499495
db_bind_text(&ins, ":file", &zPath[nPrefix+1]);
500496
db_step(&ins);
501497
--- src/vfile.c
+++ src/vfile.c
@@ -432,20 +432,16 @@
432 **
433 ** Any files or directories that match the glob pattern pIgnore are
434 ** excluded from the scan. Name matching occurs after the first
435 ** nPrefix characters are elided from the filename.
436 */
437 void vfile_scan(Blob *pPath, int nPrefix, unsigned scanFlags, Glob *pIgnore){
438 vfile_scan2(pPath, nPrefix, scanFlags, pIgnore, 0);
439 }
440
441 void vfile_scan2(
442 Blob *pPath,
443 int nPrefix,
444 unsigned scanFlags,
445 Glob *pIgnore1,
446 Glob *pIgnore2
447 ){
448 DIR *d;
449 int origSize;
450 const char *zDir;
451 struct dirent *pEntry;
@@ -490,11 +486,11 @@
490 if( glob_match(pIgnore1, &zPath[nPrefix+1]) ||
491 glob_match(pIgnore2, &zPath[nPrefix+1]) ){
492 /* do nothing */
493 }else if( file_wd_isdir(zPath)==1 ){
494 if( !vfile_top_of_checkout(zPath) ){
495 vfile_scan2(pPath, nPrefix, scanFlags, pIgnore1, pIgnore2);
496 }
497 }else if( file_wd_isfile_or_link(zPath) ){
498 if( (scanFlags & SCAN_TEMP)==0 || is_temporary_file(zUtf8) ){
499 db_bind_text(&ins, ":file", &zPath[nPrefix+1]);
500 db_step(&ins);
501
--- src/vfile.c
+++ src/vfile.c
@@ -432,20 +432,16 @@
432 **
433 ** Any files or directories that match the glob pattern pIgnore are
434 ** excluded from the scan. Name matching occurs after the first
435 ** nPrefix characters are elided from the filename.
436 */
437 void vfile_scan(
438 Blob *pPath, /* Directory to be scanned */
439 int nPrefix, /* Number of bytes in directory name */
440 unsigned scanFlags, /* Zero or more SCAN_xxx flags */
441 Glob *pIgnore1, /* Do not add files that match this GLOB */
442 Glob *pIgnore2 /* Omit files matching this GLOB too */
 
 
 
 
443 ){
444 DIR *d;
445 int origSize;
446 const char *zDir;
447 struct dirent *pEntry;
@@ -490,11 +486,11 @@
486 if( glob_match(pIgnore1, &zPath[nPrefix+1]) ||
487 glob_match(pIgnore2, &zPath[nPrefix+1]) ){
488 /* do nothing */
489 }else if( file_wd_isdir(zPath)==1 ){
490 if( !vfile_top_of_checkout(zPath) ){
491 vfile_scan(pPath, nPrefix, scanFlags, pIgnore1, pIgnore2);
492 }
493 }else if( file_wd_isfile_or_link(zPath) ){
494 if( (scanFlags & SCAN_TEMP)==0 || is_temporary_file(zUtf8) ){
495 db_bind_text(&ins, ":file", &zPath[nPrefix+1]);
496 db_step(&ins);
497
--- win/Makefile.mingw
+++ win/Makefile.mingw
@@ -94,11 +94,11 @@
9494
# here is to use the Sysinternals junction tool to create a hard
9595
# link between a "tcl-8.x" sub-directory of the Fossil source code
9696
# directory and the target Tcl directory. This removes the need to
9797
# hard-code the necessary paths in this Makefile.
9898
#
99
-TCLDIR = $(SRCDIR)/../tcl-8.6
99
+TCLDIR = $(SRCDIR)/../compat/tcl-8.6
100100
101101
#### The Tcl source code directory. This defaults to the same value as
102102
# TCLDIR macro (above), which may not be correct. This value will
103103
# only be used if the FOSSIL_TCL_SOURCE macro is defined.
104104
#
105105
--- win/Makefile.mingw
+++ win/Makefile.mingw
@@ -94,11 +94,11 @@
94 # here is to use the Sysinternals junction tool to create a hard
95 # link between a "tcl-8.x" sub-directory of the Fossil source code
96 # directory and the target Tcl directory. This removes the need to
97 # hard-code the necessary paths in this Makefile.
98 #
99 TCLDIR = $(SRCDIR)/../tcl-8.6
100
101 #### The Tcl source code directory. This defaults to the same value as
102 # TCLDIR macro (above), which may not be correct. This value will
103 # only be used if the FOSSIL_TCL_SOURCE macro is defined.
104 #
105
--- win/Makefile.mingw
+++ win/Makefile.mingw
@@ -94,11 +94,11 @@
94 # here is to use the Sysinternals junction tool to create a hard
95 # link between a "tcl-8.x" sub-directory of the Fossil source code
96 # directory and the target Tcl directory. This removes the need to
97 # hard-code the necessary paths in this Makefile.
98 #
99 TCLDIR = $(SRCDIR)/../compat/tcl-8.6
100
101 #### The Tcl source code directory. This defaults to the same value as
102 # TCLDIR macro (above), which may not be correct. This value will
103 # only be used if the FOSSIL_TCL_SOURCE macro is defined.
104 #
105
--- win/Makefile.mingw.mistachkin
+++ win/Makefile.mingw.mistachkin
@@ -94,11 +94,11 @@
9494
# here is to use the Sysinternals junction tool to create a hard
9595
# link between a "tcl-8.x" sub-directory of the Fossil source code
9696
# directory and the target Tcl directory. This removes the need to
9797
# hard-code the necessary paths in this Makefile.
9898
#
99
-TCLDIR = $(SRCDIR)/../tcl-8.6
99
+TCLDIR = $(SRCDIR)/../compat/tcl-8.6
100100
101101
#### The Tcl source code directory. This defaults to the same value as
102102
# TCLDIR macro (above), which may not be correct. This value will
103103
# only be used if the FOSSIL_TCL_SOURCE macro is defined.
104104
#
105105
--- win/Makefile.mingw.mistachkin
+++ win/Makefile.mingw.mistachkin
@@ -94,11 +94,11 @@
94 # here is to use the Sysinternals junction tool to create a hard
95 # link between a "tcl-8.x" sub-directory of the Fossil source code
96 # directory and the target Tcl directory. This removes the need to
97 # hard-code the necessary paths in this Makefile.
98 #
99 TCLDIR = $(SRCDIR)/../tcl-8.6
100
101 #### The Tcl source code directory. This defaults to the same value as
102 # TCLDIR macro (above), which may not be correct. This value will
103 # only be used if the FOSSIL_TCL_SOURCE macro is defined.
104 #
105
--- win/Makefile.mingw.mistachkin
+++ win/Makefile.mingw.mistachkin
@@ -94,11 +94,11 @@
94 # here is to use the Sysinternals junction tool to create a hard
95 # link between a "tcl-8.x" sub-directory of the Fossil source code
96 # directory and the target Tcl directory. This removes the need to
97 # hard-code the necessary paths in this Makefile.
98 #
99 TCLDIR = $(SRCDIR)/../compat/tcl-8.6
100
101 #### The Tcl source code directory. This defaults to the same value as
102 # TCLDIR macro (above), which may not be correct. This value will
103 # only be used if the FOSSIL_TCL_SOURCE macro is defined.
104 #
105
+34 -1
--- www/changes.wiki
+++ www/changes.wiki
@@ -1,8 +1,29 @@
11
<title>Change Log</title>
22
3
-<h2>Changes For Version 1.26 (as yet unreleased)</h2>
3
+<h2>Changes For Version 1.27 (as yet unreleased)</h2>
4
+ * Enhance the [/help?cmd=changes | fossil changes],
5
+ [/help?cmd=clean | fossil clean], [/help?cmd=extras | fossil extras],
6
+ [/help?cmd=ls | fossil ls] and [/help?cmd=status | fossil status] commands
7
+ to restrict operation to files and directories named on the command-line.
8
+
9
+<h2>Changes For Version 1.26 (2013-06-18)</h2>
10
+ * The argument to the --port option for the [/help?cmd=ui | fossil ui] and
11
+ [/help?cmd=server | fossil server] commands can take an IP address in addition
12
+ to the port number, causing Fossil to bind to just that one IP address.
13
+ * After prompting for a password, also ask if that password should be
14
+ remembered.
15
+ * Performance improvements to the diff engine.
16
+ * Fix the side-by-side diff engine to work better with multi-byte unicode text.
17
+ * Color-coding in the web-based annotation (blame) display. Fix the annotation
18
+ engine so that it is no longer confused by time-warps.
19
+ * The markdown formatter is now available by default and can be used for
20
+ tickets, wiki, and embedded documentation.
21
+ * Add subcommands "fossil bisect log" and "fossil bisect status" to the
22
+ [/help?cmd=bisect | fossil bisect] command, as well as other bisect enhancements.
23
+ * Enhanced defenses that prevent spiders from using excessive CPU and bandwidth.
24
+ * Consistent use of the -n or --dry-run command line options.
425
* Win32: Fossil now understands Cygwin paths containing one or more of
526
the characters <nowiki>"*:<>?|</nowiki>. Those are normally forbidden in
627
win32. This means that the win32 fossil.exe is better usable in a Cygwin
728
environment. See
829
[http://cygwin.com/cygwin-ug-net/using-specialnames.html#pathnames-specialchars].
@@ -12,11 +33,23 @@
1233
See
1334
[http://cygwin.com/cygwin-ug-net/using-specialnames.html#pathnames-casesensitive]
1435
* Enhancements to /timeline.rss, adding more flags for filtering
1536
results, including the ability to subscribe to changes made
1637
to individual tickets. For example: [/timeline.rss?y=t&tkt=12fceeec82].
38
+ * Improved handling of the differences between case-sensitive and
39
+ case-insensitive filesystems.
1740
* JSON API: added the 'status' command to report local checkout status.
41
+ * Fixes to the <tt>--args</tt> support and documented this feature in the help.
42
+ * Added [/stats_report] page.
43
+ * Added <tt>ym=YYYY-MM</tt> filter to the [/timeline?ym=2013-06].
44
+ * Fixed: <tt>config reset</tt> now re-installs default ticket report format.
45
+ * <tt>ssh://</tt> and <tt>file://</tt> protocols now ignore proxy settings.
46
+ * Added [/hash-color-test] web page.
47
+ * Cherry-pick merges are recorded internally (though no yet displayed on the
48
+ timeline graph.)
49
+ * Bring in the latest versions of SQLite, zlib, and autosetup from upstream.
50
+
1851
1952
<h2>Changes For Version 1.25 (2013-02-16)</h2>
2053
* Enhancements to ticket processing. There are now two tables: TICKET and
2154
TICKETCHNG. There is one row in TICKETCHNG for each ticket artifact.
2255
Fields from ticket artifacts go into either or both of TICKET and
2356
--- www/changes.wiki
+++ www/changes.wiki
@@ -1,8 +1,29 @@
1 <title>Change Log</title>
2
3 <h2>Changes For Version 1.26 (as yet unreleased)</h2>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4 * Win32: Fossil now understands Cygwin paths containing one or more of
5 the characters <nowiki>"*:<>?|</nowiki>. Those are normally forbidden in
6 win32. This means that the win32 fossil.exe is better usable in a Cygwin
7 environment. See
8 [http://cygwin.com/cygwin-ug-net/using-specialnames.html#pathnames-specialchars].
@@ -12,11 +33,23 @@
12 See
13 [http://cygwin.com/cygwin-ug-net/using-specialnames.html#pathnames-casesensitive]
14 * Enhancements to /timeline.rss, adding more flags for filtering
15 results, including the ability to subscribe to changes made
16 to individual tickets. For example: [/timeline.rss?y=t&tkt=12fceeec82].
 
 
17 * JSON API: added the 'status' command to report local checkout status.
 
 
 
 
 
 
 
 
 
 
18
19 <h2>Changes For Version 1.25 (2013-02-16)</h2>
20 * Enhancements to ticket processing. There are now two tables: TICKET and
21 TICKETCHNG. There is one row in TICKETCHNG for each ticket artifact.
22 Fields from ticket artifacts go into either or both of TICKET and
23
--- www/changes.wiki
+++ www/changes.wiki
@@ -1,8 +1,29 @@
1 <title>Change Log</title>
2
3 <h2>Changes For Version 1.27 (as yet unreleased)</h2>
4 * Enhance the [/help?cmd=changes | fossil changes],
5 [/help?cmd=clean | fossil clean], [/help?cmd=extras | fossil extras],
6 [/help?cmd=ls | fossil ls] and [/help?cmd=status | fossil status] commands
7 to restrict operation to files and directories named on the command-line.
8
9 <h2>Changes For Version 1.26 (2013-06-18)</h2>
10 * The argument to the --port option for the [/help?cmd=ui | fossil ui] and
11 [/help?cmd=server | fossil server] commands can take an IP address in addition
12 to the port number, causing Fossil to bind to just that one IP address.
13 * After prompting for a password, also ask if that password should be
14 remembered.
15 * Performance improvements to the diff engine.
16 * Fix the side-by-side diff engine to work better with multi-byte unicode text.
17 * Color-coding in the web-based annotation (blame) display. Fix the annotation
18 engine so that it is no longer confused by time-warps.
19 * The markdown formatter is now available by default and can be used for
20 tickets, wiki, and embedded documentation.
21 * Add subcommands "fossil bisect log" and "fossil bisect status" to the
22 [/help?cmd=bisect | fossil bisect] command, as well as other bisect enhancements.
23 * Enhanced defenses that prevent spiders from using excessive CPU and bandwidth.
24 * Consistent use of the -n or --dry-run command line options.
25 * Win32: Fossil now understands Cygwin paths containing one or more of
26 the characters <nowiki>"*:<>?|</nowiki>. Those are normally forbidden in
27 win32. This means that the win32 fossil.exe is better usable in a Cygwin
28 environment. See
29 [http://cygwin.com/cygwin-ug-net/using-specialnames.html#pathnames-specialchars].
@@ -12,11 +33,23 @@
33 See
34 [http://cygwin.com/cygwin-ug-net/using-specialnames.html#pathnames-casesensitive]
35 * Enhancements to /timeline.rss, adding more flags for filtering
36 results, including the ability to subscribe to changes made
37 to individual tickets. For example: [/timeline.rss?y=t&tkt=12fceeec82].
38 * Improved handling of the differences between case-sensitive and
39 case-insensitive filesystems.
40 * JSON API: added the 'status' command to report local checkout status.
41 * Fixes to the <tt>--args</tt> support and documented this feature in the help.
42 * Added [/stats_report] page.
43 * Added <tt>ym=YYYY-MM</tt> filter to the [/timeline?ym=2013-06].
44 * Fixed: <tt>config reset</tt> now re-installs default ticket report format.
45 * <tt>ssh://</tt> and <tt>file://</tt> protocols now ignore proxy settings.
46 * Added [/hash-color-test] web page.
47 * Cherry-pick merges are recorded internally (though no yet displayed on the
48 timeline graph.)
49 * Bring in the latest versions of SQLite, zlib, and autosetup from upstream.
50
51
52 <h2>Changes For Version 1.25 (2013-02-16)</h2>
53 * Enhancements to ticket processing. There are now two tables: TICKET and
54 TICKETCHNG. There is one row in TICKETCHNG for each ticket artifact.
55 Fields from ticket artifacts go into either or both of TICKET and
56
--- 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